One way is:
select table.*
from table
join
(
select ID, max(Date) as max_dt
from table
group by ID
) t
on table.ID= t.ID and table.Date = t.max_dt
Note that if you have multiple equally higher dates for same ID, then you will get all those rows in result
As a generic answer, not specifically directed at this task: In many cases, you can significantly speed up any program by making improvements at a high level. Like calculating data once instead of multiple times, avoiding unnecessary work completely, using caches in the best way, and so on. These things are much easier to do in a high level language.
Writing assembler code, it is possible to improve on what an optimising compiler does, but it is hard work. And once it's done, your code is much harder to modify, so it is much more difficult to add algorithmic improvements. Sometimes the processor has functionality that you cannot use from a high level language, inline assembly is often useful in these cases and still lets you use a high level language.
In the Euler problems, most of the time you succeed by building something, finding why it is slow, building something better, finding why it is slow, and so on and so on. That is very, very hard using assembler. A better algorithm at half the possible speed will usually beat a worse algorithm at full speed, and getting the full speed in assembler isn't trivial.
<form (keydown)="someMethod($event)">
<input type="text">
</form>
someMethod(event:any){
if(event.keyCode == 13){
alert('Entered Click Event!');
}else{
}
}
delete C:\Users\username\.gradle\caches
folder.
Just install http-server globally
npm install -g http-server
where ever you need to run a html file run the command http-server
For ex: your html file is in /home/project/index.html
you can do /home/project/$ http-server
That will give you a link to accessyour webpages:
http-server
Starting up http-server, serving ./
Available on:
http://127.0.0.1:8080
http://192.168.0.106:8080
One way (which I've been doing) is to setup manually :
refs: {
[string: string]: any;
stepInput:any;
}
then you can even wrap this up in a nicer getter function (e.g. here):
stepInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.stepInput);
While probably not related to your problem, I had the same issue today. As it turns out, I had enabled an URL Rewrite module to force my site to use HTTPS instead of HTTP and on my production environment, this worked just fine. But on my development system, where it runs as an application within my default site, it failed...
As it turns out, my default site had no binding for HTTPS so the rewrite module would send me from HTTP to HTTPS, yet nothing was listening to the HTTPS port...
There's a chance that you have this issue for a similar reason. This error seems to occur if there's no proper binding for the site you're trying to access...
I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)
I've tested this on Twenty Fifteen and it's working, so it should be working for you.
In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:
<div id="ajax-posts" class="row">
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 8
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="small-12 large-4 columns">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</div>
<div id="more_posts">Load More</div>
This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with
$cat_id = get_query_var('cat');
This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like
<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>
And pull the category with
var cat = $('#more_posts').data('category');
But for now, you can leave this out.
Next in functions.php I added
wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'twentyfifteen'),
));
Right after the existing wp_localize_script
. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.
At the end of the functions.php file I added the function that will load your posts:
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 8,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .= '<div class="small-12 large-4 columns">
<h1>'.get_the_title().'</h1>
<p>'.get_the_content().'</p>
</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.
If you've added your category in the loader, you'd add:
$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';
And instead of 8, you'd put $cat
. This will be in the $_POST
array, and you'll be able to use it in ajax.
Last part is the ajax itself. In functions.js I put inside the $(document).ready();
enviroment
var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
Saved it, tested it, and it works :)
Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD
UPDATE
For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;
) you can try with
$(window).on('scroll', function () {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
This should run the load_posts()
function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer
$(window).on('scroll', function(){
if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
load_posts();
}
}
});
Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100
or $('footer').offset().top
for some reason. If that should happen, just increase the number where the scroll goes to.
You can easily check it by putting console.log
s in your code and see in the inspector what they throw out
$(window).on('scroll', function () {
console.log($(window).scrollTop() + $(window).height());
console.log($(document).height() - 100);
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
And just adjust accordingly ;)
Hope this helps :) If you have any questions just ask.
Being impatient, I created a new App Pool with the same settings and used that.
--force
option worked for me I used git push origin master --force
Breaking Changes to LocalDB: Applies to SQL 2014; take a look over this article and try to use (localdb)\mssqllocaldb
as server name to connect to the LocalDB automatic instance, for example:
<connectionStrings>
<add name="ProductsContext" connectionString="Data Source=(localdb)\mssqllocaldb;
...
The article also mentions the use of 2012 SSMS to connect to the 2014 LocalDB. Which leads me to believe that you might have multiple versions of SQL installed - which leads me to point out this SO answer that suggests changing the default name of your LocalDB "instance" to avoid other version mismatch issues that might arise going forward; mentioned not as source of issue, but to raise awareness of potential clashes that multiple SQL version installed on a single dev machine might lead to ... and something to get in the habit of in order to avoid some.
Another thing worth mentioning - if you've gotten your instance in an unusable state due to tinkering with it to try and fix this problem, then it might be worth starting over - uninstall, reinstall - then try using the mssqllocaldb
value instead of v12.0
and see if that corrects your issue.
I was struggling with this, my app was installing but not complete (almost 60% I can say) in iOS8, but in iOS7.1 it was working as expected. The error message popped was:
"Cannot install at this time".
Finally Zillan's link helped me to get apple documentation. So, check:
ax.init.itunes.apple.com
is not getting blocked by your firewall/proxy (Just type this address in safari, a blank page must load). As soon as I changed the proxy it installed completely. Hope it will help someone.
We also had to develop a solution which would even work with APIs requiring authentication (see this article)
Using AngularJS in a nutshell here is how we did it:
Step 1: Create a dedicated directive
// jQuery needed, uses Bootstrap classes, adjust the path of templateUrl
app.directive('pdfDownload', function() {
return {
restrict: 'E',
templateUrl: '/path/to/pdfDownload.tpl.html',
scope: true,
link: function(scope, element, attr) {
var anchor = element.children()[0];
// When the download starts, disable the link
scope.$on('download-start', function() {
$(anchor).attr('disabled', 'disabled');
});
// When the download finishes, attach the data to the link. Enable the link and change its appearance.
scope.$on('downloaded', function(event, data) {
$(anchor).attr({
href: 'data:application/pdf;base64,' + data,
download: attr.filename
})
.removeAttr('disabled')
.text('Save')
.removeClass('btn-primary')
.addClass('btn-success');
// Also overwrite the download pdf function to do nothing.
scope.downloadPdf = function() {
};
});
},
controller: ['$scope', '$attrs', '$http', function($scope, $attrs, $http) {
$scope.downloadPdf = function() {
$scope.$emit('download-start');
$http.get($attrs.url).then(function(response) {
$scope.$emit('downloaded', response.data);
});
};
}]
});
Step 2: Create a template
<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>
Step 3: Use it
<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>
This will render a blue button. When clicked, a PDF will be downloaded (Caution: the backend has to deliver the PDF in Base64 encoding!) and put into the href. The button turns green and switches the text to Save. The user can click again and will be presented with a standard download file dialog for the file my-awesome.pdf.
For Visual Studio 2012 while debugging that error accrued
Website Menu -> Use IIS Express did it for me
In my case NDK location was the issue.
go to File->Project Structure->SDK Location
and add NDK location
Right click on your folder on your server or local machine and give full permissions to
IIS_IUSRS
that's it.
Force Stop the application in the device settings.
Those who are looking for Kotlin solution can use this method,
Here I have shared full code, and also handled enabled status. Check If Application is Installed in Android Kotlin
fun isAppInstalled(packageName: String, context: Context): Boolean {
return try {
val packageManager = context.packageManager
packageManager.getPackageInfo(packageName, 0)
true
} catch (e: PackageManager.NameNotFoundException) {
false
}
}
Old Post I know however I successfully used onlclick="" when populating a table with JSON data. Tried many other options / scripts etc before, nothing worked. Will attempt this approach elsewhere. Thanks @Dan Morris .. from 2013!
function append_json(data) {
var table=document.getElementById('gable');
data.forEach(function(object) {
var tr=document.createElement('tr');
tr.innerHTML='<td onclick="">' + object.COUNTRY + '</td>' + '<td onclick="">' + object.PoD + '</td>' + '<td onclick="">' + object.BALANCE + '</td>' + '<td onclick="">' + object.DATE + '</td>';
table.appendChild(tr);
}
);
Note: This answer is a pure Gradle answer, I use this in IntelliJ on a regular basis but I don't know how the integration is with Android Studio. I am a believer in knowing what is going on for me, so this is how I use Gradle and Android.
TL;DR Full Example - https://github.com/ethankhall/driving-time-tracker/
Disclaimer: This is a project I am/was working on.
Gradle has a defined structure ( that you can change, link at the bottom tells you how ) that is very similar to Maven if you have ever used it.
Project Root
+-- src
| +-- main (your project)
| | +-- java (where your java code goes)
| | +-- res (where your res go)
| | +-- assets (where your assets go)
| | \-- AndroidManifest.xml
| \-- instrumentTest (test project)
| \-- java (where your java code goes)
+-- build.gradle
\-- settings.gradle
If you only have the one project, the settings.gradle file isn't needed. However you want to add more projects, so we need it.
Now let's take a peek at that build.gradle file. You are going to need this in it (to add the android tools)
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.3'
}
}
Now we need to tell Gradle about some of the Android parts. It's pretty simple. A basic one (that works in most of my cases) looks like the following. I have a comment in this block, it will allow me to specify the version name and code when generating the APK.
build.gradle
apply plugin: "android"
android {
compileSdkVersion 17
/*
defaultConfig {
versionCode = 1
versionName = "0.0.0"
}
*/
}
Something we are going to want to add, to help out anyone that hasn't seen the light of Gradle yet, a way for them to use the project without installing it.
build.gradle
task wrapper(type: org.gradle.api.tasks.wrapper.Wrapper) {
gradleVersion = '1.4'
}
So now we have one project to build. Now we are going to add the others. I put them in a directory, maybe call it deps, or subProjects. It doesn't really matter, but you will need to know where you put it. To tell Gradle where the projects are you are going to need to add them to the settings.gradle.
Directory Structure:
Project Root
+-- src (see above)
+-- subProjects (where projects are held)
| +-- reallyCoolProject1 (your first included project)
| \-- See project structure for a normal app
| \-- reallyCoolProject2 (your second included project)
| \-- See project structure for a normal app
+-- build.gradle
\-- settings.gradle
settings.gradle:
include ':subProjects:reallyCoolProject1'
include ':subProjects:reallyCoolProject2'
The last thing you should make sure of is the subProjects/reallyCoolProject1/build.gradle has apply plugin: "android-library"
instead of apply plugin: "android"
.
Like every Gradle project (and Maven) we now need to tell the root project about it's dependency. This can also include any normal Java dependencies that you want.
build.gradle
dependencies{
compile 'com.fasterxml.jackson.core:jackson-core:2.1.4'
compile 'com.fasterxml.jackson.core:jackson-databind:2.1.4'
compile project(":subProjects:reallyCoolProject1")
compile project(':subProjects:reallyCoolProject2')
}
I know this seems like a lot of steps, but they are pretty easy once you do it once or twice. This way will also allow you to build on a CI server assuming you have the Android SDK installed there.
NDK Side Note: If you are going to use the NDK you are going to need something like below. Example build.gradle file can be found here: https://gist.github.com/khernyo/4226923
build.gradle
task copyNativeLibs(type: Copy) {
from fileTree(dir: 'libs', include: '**/*.so' ) into 'build/native-libs'
}
tasks.withType(Compile) { compileTask -> compileTask.dependsOn copyNativeLibs }
clean.dependsOn 'cleanCopyNativeLibs'
tasks.withType(com.android.build.gradle.tasks.PackageApplication) { pkgTask ->
pkgTask.jniDir new File('build/native-libs')
}
Sources:
Please check if the setting Generate Debug Info is Yes which under Project Propeties > Configuration Properties > Linker > Debugging tab. If not, try to change it to Yes.
Those perticular pdb's ( for ntdll.dll, mscoree.dll, kernel32.dll, etc ) are for the windows API and shouldn't be needed for simple apps. However, if you cannot find pdb's for your own compiled projects, I suggest making sure the Project Properties > Configuration Properties > Debugging > Working Directory uses the value from Project Properties > Configuration Properties > General > Output Directory .
You need to run Visual c++ in "Run as Administrator" mode.Right click on the executable and click "Run as Administrator"
I hate to post my own answer, but some answers recently have ignored the solution I posted in my own question, suggesting approaches that are nothing short of foolhardy.
In short - you do not need to edit any Windows user account privileges at all. Doing so only introduces risk. The process is entirely managed in IIS using inherited privileges.
Right-click the domain when it appears under the Sites list, and choose Edit Permissions
Under the Security tab, you will see MACHINE_NAME\IIS_IUSRS
is listed. This means that IIS automatically has read-only permission on the directory (e.g. to run ASP.Net in the site). You do not need to edit this entry.
Click the Edit button, then Add...
In the text box, type IIS AppPool\MyApplicationPoolName
, substituting MyApplicationPoolName
with your domain name or whatever application pool is accessing your site, e.g. IIS AppPool\mydomain.com
Press the Check Names button. The text you typed will transform (notice the underline):
Press OK to add the user
With the new user (your domain) selected, now you can safely provide any Modify or Write permissions
The syntax you wrote as first is not valid. You can achieve something using the follow:
var map = {"aaa": "rrr", "bbb": "ppp" /* etc */ };
Why not use a PdfPTable
object for this?
Create a fixed width table and use a float array to set the widths of the columns
PdfPTable table = new PdfPTable(10);
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 20f, 60f, 60f, 30f, 50f, 80f, 50f, 50f, 50f, 50f };
table.SetWidths(widths);
addCell(table, "SER.\nNO.", 2);
addCell(table, "TYPE OF SHIPPING", 1);
addCell(table, "ORDER NO.", 1);
addCell(table, "QTY.", 1);
addCell(table, "DISCHARGE PPORT", 1);
addCell(table, "DESCRIPTION OF GOODS", 2);
addCell(table, "LINE DOC. RECL DATE", 1);
addCell(table, "CLEARANCE DATE", 2);
addCell(table, "CUSTOM PERMIT NO.", 2);
addCell(table, "DISPATCH DATE", 2);
addCell(table, "AWB/BL NO.", 1);
addCell(table, "COMPLEX NAME", 1);
addCell(table, "G. W. Kgs.", 1);
addCell(table, "DESTINATION", 1);
addCell(table, "OWNER DOC. RECL DATE", 1);
....
private static void addCell(PdfPTable table, string text, int rowspan)
{
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
PdfPCell cell = new PdfPCell(new Phrase(text, times));
cell.Rowspan = rowspan;
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
table.AddCell(cell);
}
have a look at this tutorial too...
Running the @neverever415 answer I got:
Failure [DELETE_FAILED_INTERNAL_ERROR]
In this case check that you wrote a right package name, maybe it is a debug version like com.package_name.debug
:
adb shell pm uninstall com.package_name.debug
I had this same issue, there was no issue regarding memory in my server machine, Finally i was able to fix it by following steps
3.Find "Microsoft Excel Application" in right side.
4.Open its properties by right click
5.Under Identity tab select the option interactive user and click Ok button.
Check once again. Hope it helps
NOTE: But now you may end up with another COM error "Retrieving the COM class factory for component...". In that case Just set the Identity to this User and enter the username and password of a user who has sufficient rights. In my case I entered a user of power user group.
Ok so I took Joshoun code and made it generic. I am not sure if I should implement singleton pattern on SynchronousPost class. Maybe someone more knowledgeble can help.
FileCategory x = new FileCategory { CategoryName = "Some Bs"};
SynchronousPost<FileCategory>test= new SynchronousPost<FileCategory>();
test.PostEntity(x, "/api/ApiFileCategories");
public class SynchronousPost<T>where T :class
{
public SynchronousPost()
{
Client = new WebClient { UseDefaultCredentials = true };
}
public void PostEntity(T PostThis,string ApiControllerName)//The ApiController name should be "/api/MyName/"
{
//this just determines the root url.
Client.BaseAddress = string.Format(
(
System.Web.HttpContext.Current.Request.Url.Port != 80) ? "{0}://{1}:{2}" : "{0}://{1}",
System.Web.HttpContext.Current.Request.Url.Scheme,
System.Web.HttpContext.Current.Request.Url.Host,
System.Web.HttpContext.Current.Request.Url.Port
);
Client.Headers.Add(HttpRequestHeader.ContentType, "application/json;charset=utf-8");
Client.UploadData(
ApiControllerName, "Post",
Encoding.UTF8.GetBytes
(
JsonConvert.SerializeObject(PostThis)
)
);
}
private WebClient Client { get; set; }
}
public class ApiFileCategoriesController : ApiBaseController
{
public ApiFileCategoriesController(IMshIntranetUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
public IEnumerable<FileCategory> GetFiles()
{
return UnitOfWork.FileCategories.GetAll().OrderBy(x=>x.CategoryName);
}
public FileCategory GetFile(int id)
{
return UnitOfWork.FileCategories.GetById(id);
}
//Post api/ApileFileCategories
public HttpResponseMessage Post(FileCategory fileCategory)
{
UnitOfWork.FileCategories.Add(fileCategory);
UnitOfWork.Commit();
return new HttpResponseMessage();
}
}
I am using ninject, and repo pattern with unit of work. Anyways, the generic class above really helps.
how do I find out what is referencing System.Web.WebPages.Razor v2.0.0.0?
Just read your exception stacktrace:
Calling assembly : Microsoft.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
So it seems that you are using the Microsoft.Web.Helpers
which in turn depends on System.Web.WebPages.Razor, Version=2.0.0.0
.
This is a working example of the ACCEPTED answer above! This NetIdentity class will store both the internal host ip, as well as the local loopback. If you're on a DNS based server, as mentioned above, you may need to add some more checks, or possible go the Configuration File Route.
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
/**
* Class that allows a device to identify itself on the INTRANET.
*
* @author Decoded4620 2016
*/
public class NetIdentity {
private String loopbackHost = "";
private String host = "";
private String loopbackIp = "";
private String ip = "";
public NetIdentity(){
try{
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while(interfaces.hasMoreElements()){
NetworkInterface i = interfaces.nextElement();
if(i != null){
Enumeration<InetAddress> addresses = i.getInetAddresses();
System.out.println(i.getDisplayName());
while(addresses.hasMoreElements()){
InetAddress address = addresses.nextElement();
String hostAddr = address.getHostAddress();
// local loopback
if(hostAddr.indexOf("127.") == 0 ){
this.loopbackIp = address.getHostAddress();
this.loopbackHost = address.getHostName();
}
// internal ip addresses (behind this router)
if( hostAddr.indexOf("192.168") == 0 ||
hostAddr.indexOf("10.") == 0 ||
hostAddr.indexOf("172.16") == 0 ){
this.host = address.getHostName();
this.ip = address.getHostAddress();
}
System.out.println("\t\t-" + address.getHostName() + ":" + address.getHostAddress() + " - "+ address.getAddress());
}
}
}
}
catch(SocketException e){
}
try{
InetAddress loopbackIpAddress = InetAddress.getLocalHost();
this.loopbackIp = loopbackIpAddress.getHostName();
System.out.println("LOCALHOST: " + loopbackIp);
}
catch(UnknownHostException e){
System.err.println("ERR: " + e.toString());
}
}
public String getLoopbackHost(){
return loopbackHost;
}
public String getHost(){
return host;
}
public String getIp(){
return ip;
}
public String getLoopbackIp(){
return loopbackIp;
}
}
When I run this code I actually get a print out like this:
Software Loopback Interface 1
-127.0.0.1:127.0.0.1 - [B@19e1023e
-0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59
Broadcom 802.11ac Network Adapter
-VIKING.yourisp.com:192.168.1.142 - [B@64b8f8f4
-fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2
Microsoft Kernel Debug Network Adapter
Intel Edison USB RNDIS Device
Driver for user-mode network applications
Cisco Systems VPN Adapter for 64-bit Windows
VirtualBox Host-Only Ethernet Adapter
-VIKING:192.168.56.1 - [B@3cd1f1c8
-VIKING:fe80:0:0:0:d599:3cf0:5462:cb7%eth4 - [B@3a4afd8d
LogMeIn Hamachi Virtual Ethernet Adapter
-VIKING:25.113.118.39 - [B@1996cd68
-VIKING:2620:9b:0:0:0:0:1971:7627 - [B@3339ad8e
-VIKING:fe80:0:0:0:51bf:994d:4656:8486%eth5 - [B@555590
Bluetooth Device (Personal Area Network)
-fe80:0:0:0:4c56:8009:2bca:e16b%eth6:fe80:0:0:0:4c56:8009:2bca:e16b%eth6 - [B@3c679bde
Bluetooth Device (RFCOMM Protocol TDI)
Intel(R) Ethernet Connection (2) I218-V
-fe80:0:0:0:4093:d169:536c:7c7c%eth7:fe80:0:0:0:4093:d169:536c:7c7c%eth7 - [B@16b4a017
Microsoft Wi-Fi Direct Virtual Adapter
-fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1:fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1 - [B@8807e25
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0000
VirtualBox Host-Only Ethernet Adapter-WFP Native MAC Layer LightWeight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0001
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0002
VirtualBox Host-Only Ethernet Adapter-VirtualBox NDIS Light-Weight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0003
VirtualBox Host-Only Ethernet Adapter-QoS Packet Scheduler-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0004
VirtualBox Host-Only Ethernet Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0000
Intel(R) Ethernet Connection (2) I218-V-WFP Native MAC Layer LightWeight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0001
Intel(R) Ethernet Connection (2) I218-V-Shrew Soft Lightweight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0002
Intel(R) Ethernet Connection (2) I218-V-VirtualBox NDIS Light-Weight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0003
Intel(R) Ethernet Connection (2) I218-V-QoS Packet Scheduler-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0004
Intel(R) Ethernet Connection (2) I218-V-WFP 802.3 MAC Layer LightWeight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0005
Broadcom 802.11ac Network Adapter-WFP Native MAC Layer LightWeight Filter-0000
Broadcom 802.11ac Network Adapter-Virtual WiFi Filter Driver-0000
Broadcom 802.11ac Network Adapter-Native WiFi Filter Driver-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0003
Broadcom 802.11ac Network Adapter-Shrew Soft Lightweight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0004
Broadcom 802.11ac Network Adapter-VirtualBox NDIS Light-Weight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Broadcom 802.11ac Network Adapter-QoS Packet Scheduler-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0006
Broadcom 802.11ac Network Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0007
Microsoft Wi-Fi Direct Virtual Adapter-WFP Native MAC Layer LightWeight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-Native WiFi Filter Driver-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0002
Microsoft Wi-Fi Direct Virtual Adapter-Shrew Soft Lightweight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0003
Microsoft Wi-Fi Direct Virtual Adapter-VirtualBox NDIS Light-Weight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0004
Microsoft Wi-Fi Direct Virtual Adapter-QoS Packet Scheduler-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Microsoft Wi-Fi Direct Virtual Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0006
For my use I'm setting up a Upnp Server, it helped to understand the 'pattern' that i was looking for. Some of the objects returned are Ethernet Adapters, Network Adapters, Virtual Network Adapters, Drivers, and VPN Client Adapters. Not everything has an Address either. So you'll want to skip out on interface objects that don't.
You can also add this to the loop for the current NetworkInterface i
while(interfaces.hasMoreElements()){
Enumeration<InetAddress> addresses = i.getInetAddresses();
System.out.println(i.getDisplayName());
System.out.println("\t- name:" + i.getName());
System.out.println("\t- idx:" + i.getIndex());
System.out.println("\t- max trans unit (MTU):" + i.getMTU());
System.out.println("\t- is loopback:" + i.isLoopback());
System.out.println("\t- is PPP:" + i.isPointToPoint());
System.out.println("\t- isUp:" + i.isUp());
System.out.println("\t- isVirtual:" + i.isVirtual());
System.out.println("\t- supportsMulticast:" + i.supportsMulticast());
}
And You'll see information in your output much like this:
Software Loopback Interface 1
- name:lo
- idx:1
- max trans unit (MTU):-1
- is loopback:true
- is PPP:false
- isUp:true
- isVirtual:false
- supportsMulticast:true
-ADRESS: [127.0.0.1(VIKING-192.168.56.1)]127.0.0.1:127.0.0.1 - [B@19e1023e
-ADRESS: [0:0:0:0:0:0:0:1(VIKING-192.168.56.1)]0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59
Broadcom 802.11ac Network Adapter
- name:wlan0
- idx:2
- max trans unit (MTU):1500
- is loopback:false
- is PPP:false
- isUp:true
- isVirtual:false
- supportsMulticast:true
-ADRESS: [VIKING.monkeybrains.net(VIKING-192.168.56.1)]VIKING.monkeybrains.net:192.168.1.142 - [B@64b8f8f4
-ADRESS: [fe80:0:0:0:81fa:31d:21c9:85cd%wlan0(VIKING-192.168.56.1)]fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2
Microsoft Kernel Debug Network Adapter
- name:eth0
- idx:3
- max trans unit (MTU):-1
- is loopback:false
- is PPP:false
- isUp:false
- isVirtual:false
- supportsMulticast:true
Add the below to your manifest:
<activity android:name=".AppPreferenceActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="com.scytec.datamobile.vd.gui.android.AppPreferenceActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
All you need is a ADODB.Connection
Dim cnn As ADODB.Connection ' Requieres reference to the
Dim rs As ADODB.Recordset ' Microsoft ActiveX Data Objects Library
Set cnn = CreateObject("adodb.Connection")
cnn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Access\webforums\whiteboard2003.mdb;"
Set rs = cnn.Execute(SQLQuery) ' Retrieve the data
Thought I'd post this as an answer as it is relevant to the question and can answer it in some cases.
That same message appears also if the database does not exist!
Be sure your connection string has no misspellings, is pointing to the right server instance, etc.
Part A: Configuring your Application Pool
Suppose the Application Pool is named 'MyPool' Go to 'Advanced Settings' of the Application Pool from the IIS Manager
Scroll down to 'Identity'. Trying to edit the value will bring up a dialog box. Select 'Built-In account' and under it, select 'ApplicationPoolIdentity'.
A few lines below 'Identity', you should find 'Load User Profile'. This value should be set to 'True'.
Part B: Configuring your website
Part C: Configuring your folder
The folder in question is C:\Whatever
You should now be able to use the browse the website
Use String#trim()
method or String allRemoved = myString.replaceAll("^\\s+|\\s+$", "")
for trim both the end.
For left trim:
String leftRemoved = myString.replaceAll("^\\s+", "");
For right trim:
String rightRemoved = myString.replaceAll("\\s+$", "");
I did not test the following snippet... hopefully it will point you towards the right direction:
var jsreader = new JsonTextReader(new StringReader(stringData));
var json = (JObject)new JsonSerializer().Deserialize(jsreader);
var tableRows = from p in json["items"]
select new
{
Name = (string)p["Name"],
Age = (int)p["Age"],
Job = (string)p["Job"]
};
This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....
To cover the identities listed:
IIS_IUSRS:
This is analogous to the old IIS6 IIS_WPG
group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.
IUSR:
This account is analogous to the old IUSR_<MACHINE_NAME>
local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).
For more information about IIS_IUSRS
and IUSR
see:
DefaultAppPool:
If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name>
will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool
created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>
. You also won't see these pool accounts in your computers User Manager. See the following for more information:
ASP.NET v4.0:
-
This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool
above.
NETWORK SERVICE:
-
The NETWORK SERVICE
account is a built-in identity introduced on Windows 2003. NETWORK SERVICE
is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).
In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE
). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" />
setting in web.config
file locally (if that setting is locked then it would need to be done by an admin in the machine.config
file).
Setting <identity impersonate="true">
is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).
In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR
or a specific custom anonymous account.
LOCAL SERVICE:
The LOCAL SERVICE
account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:
LOCAL SYSTEM:
You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.
In Practice:
In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity
. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity
:
In the website you should then configure the Authentication feature:
Right click and edit the Anonymous Authentication entry:
Ensure that "Application pool identity" is selected:
When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0
pool permissions then you can either do this via Explorer:
Click the "Check Names" button:
Or you can do this using the ICACLS.EXE
utility:
icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)
...or...if you site's application pool is called BobsCatPicBlog
then:
icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)
I hope this helps clear things up.
Update:
I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:
The difference between the 'Local System' account and the 'Network Service' account?
Right click on folder.
Click Properties
Click Security Tab. You will see something like this:
Check/uncheck whatever access you need to grant to the account
Click Apply button and then OK.
Have you tried logging in with your domain prefix, e.g. DOMAIN\Username? IIS 6 defaults to using the host computer as the default domain so specifying the domain at logon may solve the problem.
Chances are you need to install .NET 4 (Which will also create a new AppPool for you)
First make sure you have IIS installed then perform the following steps:
cmd
and press ENTERcd C:\Windows\Microsoft.NET\Framework\v4.0.30319\
and press ENTER.aspnet_regiis.exe -ir
and press ENTER again.
-i
instead of -ir
. This will change their AppPools for you and steps 5-on shouldn't be necessary.(You can repeat steps 7-on for every site you want to apply .NET 4 on as well).
Additional References:
-ir
or -i
does (or the difference between them) or what other options are available. (I typically use -ir
to prevent any older sites currently running from breaking on a framework change but that's up to you.)If ApplicationPool Identity is set custom account and computer's password is changed, you have to update your password
If you want it casted to a specific type you can use this method. Most non primitive types won't by default support direct casting so you will have to handle those accordingly.
public T GetValue<T>(string registryKeyPath, string value, T defaultValue = default(T))
{
T retVal = default(T);
retVal = (T)Registry.GetValue(registryKeyPath, value, defaultValue);
return retVal;
}
Adding <validation validateIntegratedModeConfiguration="false"/>
addresses the symptom, but is not appropriate for all circumstances. Having ran around this issue a few times, I hope to help others not only overcome the problem but understand it. (Which becomes more and more important as IIS 6 fades into myth and rumor.)
Background:
This issue and the confusion surrounding it started with the introduction of ASP.NET 2.0 and IIS 7. IIS 6 had and continues to have only one pipeline mode, and it is equivalent to what IIS 7+ calls "Classic" mode. The second, newer, and recommended pipeline mode for all applications running on IIS 7+ is called "Integrated" mode.
So, what's the difference? The key difference is how ASP.NET interacts with IIS.
Classic mode is limited to an ASP.NET pipeline that cannot interact with the IIS pipeline. Essentially a request comes in and if IIS 6/Classic has been told, through server configuration, that ASP.NET can handle it then IIS hands off the request to ASP.NET and moves on. The significance of this can be gleaned from an example. If I were to authorize access to static image files, I would not be able to do it with an ASP.NET module because the IIS 6 pipeline will handle those requests itself and ASP.NET will never see those requests because they were never handed off.* On the other hand, authorizing which users can access a .ASPX page such as a request for Foo.aspx is trivial even in IIS 6/Classic because IIS always hands those requests off to the ASP.NET pipeline. In Classic mode ASP.NET does not know what it hasn't been told and there is a lot that IIS 6/Classic may not be telling it.
Integrated mode is recommended because ASP.NET handlers and modules can interact directly with the IIS pipeline. No longer does the IIS pipeline simply hand off the request to the ASP.NET pipeline, now it allows ASP.NET code to hook directly into the IIS pipeline and all the requests that hit it. This means that an ASP.NET module can not only observe requests to static image files, but can intercept those requests and take action by denying access, logging the request, etc.
Overcoming the error:
Then again maybe you are giving your application a face-lift or it was chugging along just fine until you installed a 3rd party library via NuGet, manually, or by some other means. In that case it is entirely possible httpHandlers
or httpModules
have been added to system.web
. The outcome is the error that you are seeing because validateIntegratedModeConfiguration
defaults true
. Now you have two choices:
httpHandlers
and httpModules
elements from system.web
. There are a couple possible outcomes from this:
httpHandlers
and httpModules
that NuGet packages keep adding to system.web
, hey do what you need to.validateIntegratedModeConfiguration
to false
, but at least you know what you're doing and why it matters.Good reads:
*Of course there are ways to get all kind of strange things into the ASP.NET pipeline from IIS 6/Classic via incantations like wildcard mappings, if you like that sort of thing.
i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?
Complementing the answers this is a guide to find the private key of the certificate and add the permissions.
This is the guide to get FindPrivateKey.exe found in the guide for find the private key of the certificate.
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
In my case it turned out to be commented out HTML in a master page!
Who knew that commented out HTML such as this were actually interpreted by ASP.NET!
<!--
<link rel="icon" href="../../favicon.ico">
-->
I agree with Beytan Kurt.
I had 503 thrown for both the Central Admin site as well as the SharePoint landing page. In both cases the Passwords were expired.
After resetting the password in the AD, and refreshing the Identity, CA worked but the SharePoint landing page threw a 500 error.
It turned out that the .Net Framework Version was set to V4.0. I changed it to V2.0 and it worked.
Remember after each change you need to recycle the appropriate app pool.
This may be what you are looking for...
http://technet.microsoft.com/en-us/library/cc730708%28WS.10%29.aspx
I would also advise longer term to consider a limited rights domain user, what you are trying works fine in a silo machine scenario but you are going to have to make changes if you move to another machine for the DB server.
ALTER TABLE YourTableNameHere ALTER COLUMN YourColumnNameHere VARCHAR(20)
The steps below are for Eclipse Indigo Classic Version.
If you're running this on a Linux/Unix host, the easiest solution would be to use exec()
or similar to run the command wc -l $path
. Just make sure you've sanitized $path
first to be sure that it isn't something like "/path/to/file ; rm -rf /".
If the object was recently created, you can check the Schema Changes History report, within the SQL Server Management Studio, which "provides a history of all committed DDL statement executions within the Database recorded by the default trace":
You then can search for the create statements of the objects. Among all the information displayed, there is the login name of whom executed the DDL statement.
You can sort an array using usort function.
$array = array(
array('price'=>'1000.50','product'=>'product 1'),
array('price'=>'8800.50','product'=>'product 2'),
array('price'=>'200.0','product'=>'product 3')
);
function cmp($a, $b) {
return $a['price'] > $b['price'];
}
usort($array, "cmp");
print_r($array);
Output :
Array
(
[0] => Array
(
[price] => 134.50
[product] => product 1
)
[1] => Array
(
[price] => 2033.0
[product] => product 3
)
[2] => Array
(
[price] => 8340.50
[product] => product 2
)
)
"a".localeCompare("b")
should actually return -1
since a
sorts before b
Try accessing the placeholder attribute of the input and change its value like the following:
$('#some_input_id').attr('placeholder','New Text Here');
Can also clear the placeholder if required like:
$('#some_input_id').attr('placeholder','');
When creating the TABLE under B2BOWNER
, be sure to prefix the PL/SQL function with the Schema name; i.e. B2BOWNER.F_SSC_Page_Map_Insert
.
I did not realize this until the DBAs pointed it out. I could have created the table under my root USER/SCHEMA and the PL/SQL function would have worked fine.
Because Google led me here, on Ubuntu 20.04 this works in 2020:
sudo apt install php7.4-xml
If on Apache2, remember to restart (probably not necessary):
sudo systemctl restart apache2
Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.
Difference between OpenJDK and AdoptOpenJDK
The first provides source-code, the other provides builds of that source-code.
Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:
See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.
Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.
Here is a list of considerations and motivations to consider in choosing a vendor and implementation.
Some vendors offer you a choice of JIT technologies.
To understand more about this Java ecosystem, read Java Is Still Free
assume min and max are int values, [ and ] means include this value, ( and ) means not include this value, using above to get the right value using c++ rand()
reference: for ()[] define, visit:
https://en.wikipedia.org/wiki/Interval_(mathematics)
for rand and srand function or RAND_MAX define, visit:
http://en.cppreference.com/w/cpp/numeric/random/rand
[min, max]
int randNum = rand() % (max - min + 1) + min
(min, max]
int randNum = rand() % (max - min) + min + 1
[min, max)
int randNum = rand() % (max - min) + min
(min, max)
int randNum = rand() % (max - min - 1) + min + 1
Very simple use this just in one line:
byte[] imgdata = File.ReadAllBytes(@"C:\download.png");
The new (in 2014) tidyr
package also does this simply, with gather()
/spread()
being the terms for melt
/cast
.
Edit: Now, in 2019, tidyr v 1.0 has launched and set spread
and gather
on a deprecation path, preferring instead pivot_wider
and pivot_longer
, which you can find described in this answer. Read on if you want a brief glimpse into the brief life of spread/gather
.
library(tidyr)
spread(dat1, key = numbers, value = value)
From github,
tidyr
is a reframing ofreshape2
designed to accompany the tidy data framework, and to work hand-in-hand withmagrittr
anddplyr
to build a solid pipeline for data analysis.Just as
reshape2
did less than reshape,tidyr
does less thanreshape2
. It's designed specifically for tidying data, not the general reshaping thatreshape2
does, or the general aggregation that reshape did. In particular, built-in methods only work for data frames, andtidyr
provides no margins or aggregation.
What about
import operator
auths = Author.objects.order_by('-score')[:30]
ordered = sorted(auths, key=operator.attrgetter('last_name'))
In Django 1.4 and newer you can order by providing multiple fields.
Reference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by
order_by(*fields)
By default, results returned by a QuerySet
are ordered by the ordering tuple given by the ordering
option in the model’s Meta. You can override this on a per-QuerySet basis by using the order_by
method.
Example:
ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]
The result above will be ordered by score
descending, then by last_name
ascending. The negative sign in front of "-score"
indicates descending order. Ascending order is implied.
You can do it using the foreach loop
DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];
foreach(DataRow row in dr_art_line_2.Rows)
{
QuantityInIssueUnit_value = Convert.ToInt32(row["columnname"]);
}
(Basically what @user3464070 already said)
For Mac:
cd ~/Library/Android/sdk
# download latest tools
curl -O https://dl.google.com/android/repository/tools_r25.2.3-macosx.zip
# overwrite existing tools folder without prompting
unzip -o tools_r25.2.3-macosx.zip
# clean up
rm tools_r25.2.3-macosx.zip
go to C:xampp\apache\conf\extra\httpd-ssl.conf
Find the line where it says Listen 443, change it to Listen 4330 and restart your computer
[![enter image description here][2]][2]
There are few examples for using JSONP which include error handling.
However, please note that the error-event is not triggered when using JSONP! See: http://api.jquery.com/jQuery.ajax/ or jQuery ajax request using jsonp error
Session.Abandon()
destroys the session and the Session_OnEnd event is triggered.
Session.Clear()
just removes all values (content) from the Object. The session with the same key is still alive.
So, if you use Session.Abandon()
, you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Use Session.Clear()
, if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.
Perhaps you'd consider using android:shadowColor, android:shadowDx
, android:shadowDy
, android:shadowRadius
; alternatively setShadowLayer() ?
You can use NSNotification
Add a post method in your custom class:
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
Add an observer in your ViewController:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOFReceivedNotication:", name:"NotificationIdentifier", object: nil)
Add function in you ViewController:
func methodOFReceivedNotication(notification: NSNotification){
self.performSegueWithIdentifier("yourIdentifierInStoryboard", sender: self)
}
You should create an installer, as mentioned before. Even though it is also possible to let py2exe bundle everything into a single executable, by setting bundle_files option to 1 and the zipfile keyword argument to None, I don't recommend this for PyGTK applications.
That's because of GTK+ tries to load its data files (locals, themes, etc.) from the directory it was loaded from. So you have to make sure that the directory of your executable contains also the libraries used by GTK+ and the directories lib, share and etc from your installation of GTK+. Otherwise you will get problems running your application on a machine where GTK+ is not installed system-wide.
For more details read my guide to py2exe for PyGTK applications. It also explains how to bundle everything, but GTK+.
Appending to and copying slices
The variadic function
append
appends zero or more valuesx
tos
of typeS
, which must be a slice type, and returns the resulting slice, also of typeS
. The valuesx
are passed to a parameter of type...T
whereT
is the element type ofS
and the respective parameter passing rules apply. As a special case, append also accepts a first argument assignable to type[]byte
with a second argument ofstring
type followed by...
. This form appends the bytes of the string.append(s S, x ...T) S // T is the element type of S s0 := []int{0, 0} s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2} s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7} s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
Passing arguments to ... parameters
If
f
is variadic with final parameter type...T
, then within the function the argument is equivalent to a parameter of type[]T
. At each call off
, the argument passed to the final parameter is a new slice of type[]T
whose successive elements are the actual arguments, which all must be assignable to the typeT
. The length of the slice is therefore the number of arguments bound to the final parameter and may differ for each call site.
The answer to your question is example s3 := append(s2, s0...)
in the Go Programming Language Specification. For example,
s := append([]int{1, 2}, []int{3, 4}...)
As of 6-6-15 the Web Root location is at /tmp/deployment/application/ROOT using Tomcat.
Anybody working with nullable types, Value
is required to use CompareTo
.
objListOrder.Sort((x, y) => x.YourNullableType.Value.CompareTo(y.YourNullableType.Value));
With this
npm install --save core-js@^3
you now get the error
"core-js@<3 is no longer maintained and not recommended for usage due to the number of
issues. Please, upgrade your dependencies to the actual version of core-js@3"
so you might want to instead try
npm install --save core-js@3
if you're reading this post June 9 2020.
Try this that works for me:
$('#bar').mousedown();
I have replace your Code and it works well
$sum=0;
while ($row = mysql_fetch_assoc($result)){
$value = $row['Value'];
$sum += $value;
}
echo $sum;
You could set up a cron job to run on every day of the month, and have it run a shell script like the following. This script works out whether tomorrow's day number is less than today's (i.e. if tomorrow is a new month), and then does whatever you want.
TODAY=`date +%d`
TOMORROW=`date +%d -d "1 day"`
# See if tomorrow's day is less than today's
if [ $TOMORROW -lt $TODAY ]; then
echo "This is the last day of the month"
# Do stuff...
fi
In my work experience, JavaScript is much better to redirect.
It depends on how you want to change the location. If you want to log your website in users history, use window.location.href='ur website';
. Otherwise to do it without logging in history, use window.location.replace("your website");
.
I solved this issue for me by checking that Maven Dependencies were being deployed in Deployment Assembly. In my case they were not.
Adding it fixed the problem.
I'm getting
SecurityError: The operation is insecure.
when using canvas.toDataURL('image/jpg');
in safari browser
Having the same chore on windows 10, and windows server 2012. I found the following solution:
echo quit |sqlplus schemaName/schemaPassword@sid @plsqlScript.sql > outputFile.log
echo quit |
send the quit command to exit sqlplus
after the script completes
sqlplus schemaName/schemaPassword@sid @plsqlScript.sql
execute plssql script plsqlScript.sql
in schema schemaName
with password schemaPassword
connecting to SID sid
> outputFile.log
redirect sqlplus output to log file outputFile.log
I had the same issue. I used Worksheet
instead of Worksheets
and it was resolved. Not sure what the difference is between them.
Download the Visual C++ Redistributable 2015
Updated links to VC++ file:
By using java 8 java.time.LocalDate
String date = "1/13/2012";
LocalDate lastDayOfMonth = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/dd/yyyy"))
.with(TemporalAdjusters.lastDayOfMonth());
getResources()
works only when you're in Activity
or Fragment
class.
use:
Resources.getSystem().getString(android.R.string.somecommonstuff)
My solution. The JSONServer is a class I wrote for running an HttpListener server in a console window.
class Program
{
public static JSONServer srv = null;
static void Main(string[] args)
{
Console.WriteLine("NLPS Core Server");
srv = new JSONServer(100);
srv.Start();
InputLoopProcessor();
while(srv.IsRunning)
{
Thread.Sleep(250);
}
}
private static async Task InputLoopProcessor()
{
string line = "";
Console.WriteLine("Core NLPS Server: Started on port 8080. " + DateTime.Now);
while(line != "quit")
{
Console.Write(": ");
line = Console.ReadLine().ToLower();
Console.WriteLine(line);
if(line == "?" || line == "help")
{
Console.WriteLine("Core NLPS Server Help");
Console.WriteLine(" ? or help: Show this help.");
Console.WriteLine(" quit: Stop the server.");
}
}
srv.Stop();
Console.WriteLine("Core Processor done at " + DateTime.Now);
}
}
$(function() { $( "#draggable" ).draggable({ containment: "window" }); });
of this code does not display. Full code and Demo: http://www.limitsizbilgi.com/div-tasima-surukle-birak-div-drag-and-drop-jquery.html
In order to limit the element inside its parent:
$( "#draggable" ).draggable({ containment: "window" });
This worked for me:
$('input[name="sort_order"]').attr('value','XXX');
Use ThisWorkbook
which will refer to the original workbook which holds the code.
Alternatively at code start
Dim Wb As Workbook
Set Wb = ActiveWorkbook
sample code that activates all open books before returning to ThisWorkbook
Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
Wb2.Activate
Next
Wb.Activate
End Sub
I needed a variation on this, which I expect will be useful to others:
function diffs() {
diff "${@:3}" <(sort "$1") <(sort "$2")
}
The "${@:3}"
part means all the members of the array starting at 3. So this function implements a sorted diff by passing the first two arguments to diff through sort and then passing all other arguments to diff, so you can call it similarly to diff:
diffs file1 file2 [other diff args, e.g. -y]
I display images in windows forms when I put it in Load event like this:
private void Form1_Load( object sender , EventArgs e )
{
pictureBox1.ImageLocation = "./image.png"; //path to image
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
}
If you want to delete all .git folders in a project use the following command:
find . -type f | grep -i "\.git" | xargs rm
This will also delete all the .git folders and .gitignore files from all subfolders
Put the following code before int main()
:
using namespace std;
And you will be able to use cout
.
For example:
#include<iostream>
using namespace std;
int main(){
char t = 'f';
char *t1;
char **t2;
cout<<t;
return 0;
}
Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/
Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std;
at the top of your code. For detailed correct approach, please read the answers to this related SO question.
You need to implement a javax.xml.ws.handler.LogicalHandler, this handler then needs to be referenced in a handler configuration file, which in turn is referenced by an @HandlerChain annotation in your service endpoint (interface or implementation). You can then either output the message via system.out or a logger in your processMessage implementation.
See
http://java.sun.com/mailers/techtips/enterprise/2006/TechTips_June06.html
Bulk user creation with set_password
I you are creating several test users, bulk_create
is much faster, but we can't use create_user
with it.
set_password
is another way to generate the hashed passwords:
def users_iterator():
for i in range(nusers):
is_superuser = (i == 0)
user = User(
first_name='First' + str(i),
is_staff=is_superuser,
is_superuser=is_superuser,
last_name='Last' + str(i),
username='user' + str(i),
)
user.set_password('asdfqwer')
yield user
class Command(BaseCommand):
def handle(self, **options):
User.objects.bulk_create(iter(users_iterator()))
Question specific about password hashing: How to use Bcrypt to encrypt passwords in Django
Tested in Django 1.9.
You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?
Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.
How a character is represented is up to the renderer, but the server may also strip out certain characters before sending the document.
You can also have untitled YouTube videos like https://www.youtube.com/watch?v=dmBvw8uPbrA by using the Unicode character ZERO WIDTH NON-JOINER (U+200C), or ‌
in HTML. The code block below should contain that character:
??
since python-daemon has not yet supported python 3.x, and from what can be read on the mailing list, it may never will, i have written a new implementation of PEP 3143: pep3143daemon
pep3143daemon should support at least python 2.6, 2.7 and 3.x
It also contains a PidFile class.
The library only depends on the standard library and on the six module.
It can be used as a drop in replacement for python-daemon.
Here is the documentation.
You can use d6tstack which creates the table for you and is faster than pd.to_sql() because it uses native DB import commands. It supports Postgres as well as MYSQL and MS SQL.
import pandas as pd
df = pd.read_csv('table.csv')
uri_psql = 'postgresql+psycopg2://usr:pwd@localhost/db'
d6tstack.utils.pd_to_psql(df, uri_psql, 'table')
It is also useful for importing multiple CSVs, solving data schema changes and/or preprocess with pandas (eg for dates) before writing to db, see further down in examples notebook
d6tstack.combine_csv.CombinerCSV(glob.glob('*.csv'),
apply_after_read=apply_fun).to_psql_combine(uri_psql, 'table')
If you really want a thematic break, by all means use the <hr>
tag.
If you just want a design line, you could use something like the css class
.hline-bottom {
padding-bottom: 10px;
border-bottom: 2px solid #000; /* whichever color you prefer */
}
and use it like
<div class="block_1 hline-bottom">Cheese</div>
If you don't want to have to add the stop propagation to all links this works as well. A bit more scalable.
$scope.hideOverlay( $event ){
// only hide the overlay if we click on the actual div
if( $event.target.className.indexOf('overlay') )
// hide overlay logic
}
It looks like you already have a solution. To make things easier, why not just put your command in a bash script (with a short name) and just run that instead of typing out that 'long' command every time?
This one works for me.
It is simpler then Rj0078's answer in this question (https://stackoverflow.com/a/42556648/11211963), but that one is worked as well.
It shows a dialog like this:
(Written in Kotlin)
googleApiClient = GoogleApiClient.Builder(context!!)
.addApi(LocationServices.API).build()
googleApiClient!!.connect()
locationRequest = LocationRequest.create()
locationRequest!!.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest!!.interval = 30 * 1000.toLong()
locationRequest!!.fastestInterval = 5 * 1000.toLong()
val builder = LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest!!)
builder.setAlwaysShow(true)
result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build())
result!!.setResultCallback { result ->
val status: Status = result.status
when (status.statusCode) {
LocationSettingsStatusCodes.SUCCESS -> {
// Do something
}
LocationSettingsStatusCodes.RESOLUTION_REQUIRED ->
try {
startResolutionForResult(),
status.startResolutionForResult(
activity,
REQUEST_LOCATION
)
} catch (e: SendIntentException) {
}
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
// Do something
}
}
}
If you're:
One option is scripting the terminal itself if your use case is more app monitoring / management.
For example I recently did the following. Granted it's Mac specific, iTerm specific, and relies on a deprecated Apple Script API (iTerm has a newer Python option). It doesn't win any elegance awards but gets the job done.
#!/bin/sh
root_path="~/root-path"
auth_api_script="$root_path/auth-path/auth-script.sh"
admin_api_proj="$root_path/admin-path/admin.csproj"
agent_proj="$root_path/agent-path/agent.csproj"
dashboard_path="$root_path/dashboard-web"
osascript <<THEEND
tell application "iTerm"
set newWindow to (create window with default profile)
tell current session of newWindow
set name to "Auth API"
write text "pushd $root_path && $auth_api_script"
end tell
tell newWindow
set newTab to (create tab with default profile)
tell current session of newTab
set name to "Admin API"
write text "dotnet run --debug -p $admin_api_proj"
end tell
end tell
tell newWindow
set newTab to (create tab with default profile)
tell current session of newTab
set name to "Agent"
write text "dotnet run --debug -p $agent_proj"
end tell
end tell
tell newWindow
set newTab to (create tab with default profile)
tell current session of newTab
set name to "Dashboard"
write text "pushd $dashboard_path; ng serve -o"
end tell
end tell
end tell
THEEND
Set is just an interface. In order to retain order, you have to use a specific implementation of that interface and the sub-interface SortedSet, for example TreeSet or LinkedHashSet. You can wrap your Set this way:
Set myOrderedSet = new LinkedHashSet(mySet);
httpOnly is supported as of Tomcat 6.0.19 and Tomcat 5.5.28.
See the changelog entry for bug 44382.
The last comment for bug 44382 states, "this has been applied to 5.5.x and will be included in 5.5.28 onwards." However, it does not appear that 5.5.28 has been released.
The httpOnly functionality can be enabled for all webapps in conf/context.xml:
<Context useHttpOnly="true">
...
</Context>
My interpretation is that it also works for an individual context by setting it on the desired Context entry in conf/server.xml (in the same manner as above).
I don't think you can set arbitrarily sized images on any of the existing button classes. If you want a simple image behaving like a button, you can write your own QAbstractButton-subclass, something like:
class ImageButton : public QAbstractButton {
Q_OBJECT
public:
...
void setPixmap( const QPixmap& pm ) { m_pixmap = pm; update(); }
QSize sizeHint() const { return m_pixmap.size(); }
protected:
void paintEvent( QPaintEvent* e ) {
QPainter p( this );
p.drawPixmap( 0, 0, m_pixmap );
}
};
Someone has mentioned that if you are using terminal and your current directory is inside the path which you want to unmount, you will get the error.
As a complementary, in this case, your lsof | grep path-to-be-unmounted
must have below output:
bash ... path-to-be-unmounted
To expand on ccc's answer, if you want to incorporate querying the card with a script, here is information on Nvidia site on how to do so:
https://nvidia.custhelp.com/app/answers/detail/a_id/3751/~/useful-nvidia-smi-queries
Also, I found this thread researching powershell. Here is an example command that runs the utility to get the true memory available on the GPU to get you started.
# get gpu metrics
$cmd = "& 'C:\Program Files\NVIDIA Corporation\NVSMI\nvidia-smi' --query-gpu=name,utilization.memory,driver_version --format=csv"
$gpuinfo = invoke-expression $cmd | ConvertFrom-CSV
$gpuname = $gpuinfo.name
$gpuutil = $gpuinfo.'utilization.memory [%]'.Split(' ')[0]
$gpuDriver = $gpuinfo.driver_version
If you want to trim all spaces, only in lines that have a comma, and use awk
, then the following will work for you:
awk -F, '/,/{gsub(/ /, "", $0); print} ' input.txt
If you only want to remove spaces in the second column, change the expression to
awk -F, '/,/{gsub(/ /, "", $2); print$1","$2} ' input.txt
Note that gsub
substitutes the character in //
with the second expression, in the variable that is the third parameter - and does so in-place
- in other words, when it's done, the $0
(or $2
) has been modified.
Full explanation:
-F, use comma as field separator
(so the thing before the first comma is $1, etc)
/,/ operate only on lines with a comma
(this means empty lines are skipped)
gsub(a,b,c) match the regular expression a, replace it with b,
and do all this with the contents of c
print$1","$2 print the contents of field 1, a comma, then field 2
input.txt use input.txt as the source of lines to process
EDIT I want to point out that @BMW's solution is better, as it actually trims only leading and trailing spaces with two successive gsub
commands. Whilst giving credit I will give an explanation of how it works.
gsub(/^[ \t]+/,"",$2); - starting at the beginning (^) replace all (+ = zero or more, greedy)
consecutive tabs and spaces with an empty string
gsub(/[ \t]+$/,"",$2)} - do the same, but now for all space up to the end of string ($)
1 - ="true". Shorthand for "use default action", which is print $0
- that is, print the entire (modified) line
I've had a go at putting together a multiprocessing example of file text searching. This is my first effort at using the multiprocessing module; and I'm a python n00b. Comments quite welcome. I'll have to wait until at work to test on really big files. It should be faster on multi core systems than single core searching. Bleagh! How do I stop the processes once the text has been found and reliably report line number?
import multiprocessing, os, time
NUMBER_OF_PROCESSES = multiprocessing.cpu_count()
def FindText( host, file_name, text):
file_size = os.stat(file_name ).st_size
m1 = open(file_name, "r")
#work out file size to divide up to farm out line counting
chunk = (file_size / NUMBER_OF_PROCESSES ) + 1
lines = 0
line_found_at = -1
seekStart = chunk * (host)
seekEnd = chunk * (host+1)
if seekEnd > file_size:
seekEnd = file_size
if host > 0:
m1.seek( seekStart )
m1.readline()
line = m1.readline()
while len(line) > 0:
lines += 1
if text in line:
#found the line
line_found_at = lines
break
if m1.tell() > seekEnd or len(line) == 0:
break
line = m1.readline()
m1.close()
return host,lines,line_found_at
# Function run by worker processes
def worker(input, output):
for host,file_name,text in iter(input.get, 'STOP'):
output.put(FindText( host,file_name,text ))
def main(file_name,text):
t_start = time.time()
# Create queues
task_queue = multiprocessing.Queue()
done_queue = multiprocessing.Queue()
#submit file to open and text to find
print 'Starting', NUMBER_OF_PROCESSES, 'searching workers'
for h in range( NUMBER_OF_PROCESSES ):
t = (h,file_name,text)
task_queue.put(t)
#Start worker processes
for _i in range(NUMBER_OF_PROCESSES):
multiprocessing.Process(target=worker, args=(task_queue, done_queue)).start()
# Get and print results
results = {}
for _i in range(NUMBER_OF_PROCESSES):
host,lines,line_found = done_queue.get()
results[host] = (lines,line_found)
# Tell child processes to stop
for _i in range(NUMBER_OF_PROCESSES):
task_queue.put('STOP')
# print "Stopping Process #%s" % i
total_lines = 0
for h in range(NUMBER_OF_PROCESSES):
if results[h][1] > -1:
print text, 'Found at', total_lines + results[h][1], 'in', time.time() - t_start, 'seconds'
break
total_lines += results[h][0]
if __name__ == "__main__":
main( file_name = 'testFile.txt', text = 'IPI1520' )
In fact, the original S3 auth does allow for the content to be signed, albeit with a weak MD5 signature. You can simply enforce their optional practice of including a Content-MD5 header in the HMAC (string to be signed).
http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html
Their new v4 authentication scheme is more secure.
http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
That's answered fully here for WinForms: DataGridViewButtonColumn Class
and here: How to: Respond to Button Events in a GridView Control
for Asp.Net depending on the control you're actually using. (Your question says DataGrid, but you're developing a Windows app, so the control you'd be using there is a DataGridView...)
You must install middleware to serve the favicon.
I tried this just now:
app.use(express.favicon(path.join(__dirname, 'public','images','favicon.ico')));
and got this error message back:
Error: Most middleware (like favicon) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
I think we can take that as being definitive.
I think this would be a more simpler way of outputting your results.
Sorry for using my own data should be easy to replace .
$query = "SELECT * FROM category ";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result))
{
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo $cat_id . " " . $cat_title ."<br>";
}
This would output :
You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important
.
#zoomTarget .slikezamenjanje img {
max-height: auto;
padding-right: 0px;
}
I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.
For example, all CSS height
and width
attributes default to auto
.
I actually tried to implement connection pooling on the django end using:
https://github.com/gmcguire/django-db-pool
but I still received this error, despite lowering the number of connections available to below the standard development DB quota of 20 open connections.
There is an article here about how to move your postgresql database to the free/cheap tier of Amazon RDS. This would allow you to set max_connections
higher. This will also allow you to pool connections at the database level using PGBouncer.
https://www.lewagon.com/blog/how-to-migrate-heroku-postgres-database-to-amazon-rds
UPDATE:
Heroku responded to my open ticket and stated that my database was improperly load balanced in their network. They said that improvements to their system should prevent similar problems in the future. Nonetheless, support manually relocated my database and performance is noticeably improved.
rebellion's answer above won't actually work, because to CSS, 'background-position' is actually shorthand for 'background-position-x' and 'background-position-y' so the correct version of his code would be:
$(document).ready(function(){
$('#submenu li').hover(function(){
$('#carousel').css('background-position-x', newValueX);
$('#carousel').css('background-position-y', newValue);
}, function(){
$('#carousel').css('background-position-x', oldValueX);
$('#carousel').css('background-position-y', oldValueY);
});
});
It took about 4 hours of banging my head against it to come to that aggravating realization.
src.prefix1.prefix.packagename1 src.prefix1.prefix.packagename2
Click Build path --> Remove from build path.
Now go the folder prefix1 in the folder section of your project.
Right click on it --> Build path --> Use as source folder.
Done. The package folder wont show any error now. If it still shows, just restart the project.
It's just shorthand for $(document).ready()
, as in: $(document).ready(function() {
YOUR_CODE_HERE
});
. Sometimes you have to use it because your function is running before the DOM finishes loading.
Everything is explained here: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
Try this..
select starttime,endtime, case
when DATEDIFF(minute,starttime,endtime) < 60 then DATEDIFF(minute,starttime,endtime)
when DATEDIFF(minute,starttime,endtime) >= 60
then '60,'+ cast( (cast(DATEDIFF(minute,starttime,endtime) as int )-60) as nvarchar(50) )
end from TestTable123416
All You need is DateDiff..
I found that because I was using a network-oriented command in my rc.local
, sometimes it would fail. I fixed this by putting sleep 3
at the top of my script. I don't know why but it seems when the script is run the network interfaces aren't properly configured or something, and this just allows some time for the DHCP server or something. I don't fully understand but I suppose you could give it a try.
You can automatically encode into Json, your complex entity with:
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
JsonEncoder()));
$json = $serializer->serialize($entity, 'json');
I got this exception while coping a object(variable) Matrix Array into Excel sheet. The solution to this is, Matrix array Index(i,j) must start from (0,0) whereas Excel sheet should start with Matrix Array index (i,j) from (1,1) .
I hope you this concept.
Old question but throwing my solution into the ring for completeness. I needed this when I needed a specific find but a different create if it doesn't exist.
def self.find_by_or_create_with(args, attributes) # READ CAREFULLY! args for finding, attributes for creating!
obj = self.find_or_initialize_by(args)
return obj if obj.persisted?
return obj if obj.update_attributes(attributes)
end
I have made this program and here is the bit of code that actually calculates the check digit in my program
#Get the 10 digit number
number=input("Please enter ISBN number: ")
#Explained below
no11 = (((int(number[0])*11) + (int(number[1])*10) + (int(number[2])*9) + (int(number[3])*8)
+ (int(number[4])*7) + (int(number[5])*6) + (int(number[6])*5) + (int(number[7])*4) +
(int(number[8])*3) + (int(number[9])*2))/11)
#Round to 1 dp
no11 = round(no11, 1)
#explained below
no11 = str(no11).split(".")
#get the remainder and check digit
remainder = no11[1]
no11 = (11 - int(remainder))
#Calculate 11 digit ISBN
print("Correct ISBN number is " + number + str(no11))
Its a long line of code, but it splits the number up, multiplies the digits by the appropriate amount, adds them together and divides them by 11, in one line of code. The .split() function just creates a list (being split at the decimal) so you can take the 2nd item in the list and take that from 11 to find the check digit. This could also be made even more efficient by changing these two lines:
remainder = no11[1]
no11 = (11 - int(remainder))
To this:
no11 = (11 - int(no11[1]))
Hope this helps :)
Using Apache Commons Lang:
!StringUtils.isAlphanumeric(String)
Alternativly iterate over String's characters and check with:
!Character.isLetterOrDigit(char)
You've still one problem left:
Your example string "abcdefà" is alphanumeric, since à
is a letter. But I think you want it to be considered non-alphanumeric, right?!
So you may want to use regular expression instead:
String s = "abcdefà";
Pattern p = Pattern.compile("[^a-zA-Z0-9]");
boolean hasSpecialChar = p.matcher(s).find();
In Python, you can't just embed arbitrary Python expressions into literal strings and have it substitute the value of the string. You need to either:
sys.stderr.write("Usage: " + sys.argv[0])
or
sys.stderr.write("Usage: %s" % sys.argv[0])
Also, you may want to consider using the following syntax of print
(for Python earlier than 3.x):
print >>sys.stderr, "Usage:", sys.argv[0]
Using print
arguably makes the code easier to read. Python automatically adds a space between arguments to the print
statement, so there will be one space after the colon in the above example.
In Python 3.x, you would use the print
function:
print("Usage:", sys.argv[0], file=sys.stderr)
Finally, in Python 2.6 and later you can use .format
:
print >>sys.stderr, "Usage: {0}".format(sys.argv[0])
$image="img_name.jpg";
$pdf =new FPDF();
$pdf-> AddPage();
$pdf-> SetFont("Arial","B",10);
$pdf-> Image('profileimage/'.$image,100,15,35,35);
EDIT: as_matrix
is deprecated since version 0.23.0
You can use the built in values
or to_numpy
(recommended option) method on the dataframe:
In [8]:
df.to_numpy()
Out[8]:
array([[ 0.9, 7. , 5.2, ..., 13.3, 13.5, 8.9],
[ 0.9, 7. , 5.2, ..., 13.3, 13.5, 8.9],
[ 0.8, 6.1, 5.4, ..., 15.9, 14.4, 8.6],
...,
[ 0.2, 1.3, 2.3, ..., 16.1, 16.1, 10.8],
[ 0.2, 1.3, 2.4, ..., 16.5, 15.9, 11.4],
[ 0.2, 1.3, 2.4, ..., 16.5, 15.9, 11.4]])
If you explicitly want lists and not a numpy array add .tolist()
:
df.to_numpy().tolist()
After all i got the answer thanks to wikisona, first the beans:
@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
return new TomcatEmbeddedServletContainerFactory() {
@Override
protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
Tomcat tomcat) {
tomcat.enableNaming();
return super.getTomcatEmbeddedServletContainer(tomcat);
}
@Override
protected void postProcessContext(Context context) {
ContextResource resource = new ContextResource();
resource.setName("jdbc/myDataSource");
resource.setType(DataSource.class.getName());
resource.setProperty("driverClassName", "your.db.Driver");
resource.setProperty("url", "jdbc:yourDb");
context.getNamingResources().addResource(resource);
}
};
}
@Bean(destroyMethod="")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:comp/env/jdbc/myDataSource");
bean.setProxyInterface(DataSource.class);
bean.setLookupOnStartup(false);
bean.afterPropertiesSet();
return (DataSource)bean.getObject();
}
the full code it's here: https://github.com/wilkinsona/spring-boot-sample-tomcat-jndi
response.session doesn't work anymore because response.authResponse is the new way to access the response content after the oauth migration.
Check this for details:
SDKs & Tools › JavaScript SDK › FB.login
Try this:
delete from your_table;
delete from sqlite_sequence where name='your_table';
SQLite keeps track of the largest ROWID that a table has ever held using the special
SQLITE_SEQUENCE
table. TheSQLITE_SEQUENCE
table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.
Apply the following in your Theme for the Activity in AndroidManifest.xml
:
<activity android:name=".Activity"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
That should do the trick.
To cherry pick from a commit id up to the tip of the branch, you can use:
git cherry-pick commit_id^..branch_name
You may also try mongoosejs's lean() :
UserModel.find().lean().exec(function (err, users) {
return res.end(JSON.stringify(users));
}
There are lot of different Timers in the .NET BCL:
When to use which?
System.Timers.Timer
, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.System.Threading.Timer
, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.System.Windows.Forms.Timer
(.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.System.Web.UI.Timer
(.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.System.Windows.Threading.DispatcherTimer
, a timer that's integrated into the Dispatcher queue. This timer is processed with a specified priority at a specified time interval.Some of them needs explicit Start
call to begin ticking (for example System.Timers
, System.Windows.Forms
). And an explicit Stop
to finish ticking.
using TimersTimer = System.Timers.Timer;
static void Main(string[] args)
{
var timer = new TimersTimer(1000);
timer.Elapsed += (s, e) => Console.WriteLine("Beep");
Thread.Sleep(1000); //1 second delay
timer.Start();
Console.ReadLine();
timer.Stop();
}
While on the other hand there are some Timers (like: System.Threading
) where you don't need explicit Start
and Stop
calls. (The provided delegate will run a background thread.) Your timer will tick until you or the runtime dispose it.
So, the following two versions will work in the same way:
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
Console.ReadLine();
}
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
StartTimer();
Console.ReadLine();
}
static void StartTimer()
{
var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
But if your timer
disposed then it will stop ticking obviously.
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
StartTimer();
GC.Collect(0);
Console.ReadLine();
}
static void StartTimer()
{
var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
You can find out occurrence of '_' in source string by using string functions. find() function takes 2 arguments , first - string whose occurrences we want to find out and second argument takes starting position.While loop is use to find out occurrence till the end of source string.
example:
string str2 = "_";
string strData = "bla_bla_blabla_bla_";
size_t pos = 0,pos2;
while ((pos = strData.find(str2, pos)) < strData.length())
{
printf("\n%d", pos);
pos += str2.length();
}
For space separated strings, then you can do this:
std::string s = "What is the right way to split a string into a vector of strings";
std::stringstream ss(s);
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
std::copy(vstrings.begin(), vstrings.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
Output:
What
is
the
right
way
to
split
a
string
into
a
vector
of
strings
struct tokens: std::ctype<char>
{
tokens(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table()
{
typedef std::ctype<char> cctype;
static const cctype::mask *const_rc= cctype::classic_table();
static cctype::mask rc[cctype::table_size];
std::memcpy(rc, const_rc, cctype::table_size * sizeof(cctype::mask));
rc[','] = std::ctype_base::space;
rc[' '] = std::ctype_base::space;
return &rc[0];
}
};
std::string s = "right way, wrong way, correct way";
std::stringstream ss(s);
ss.imbue(std::locale(std::locale(), new tokens()));
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
std::copy(vstrings.begin(), vstrings.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
Output:
right
way
wrong
way
correct
way
strRetMsg ="<script>window.location.href = '../Other/Home.htm';</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", strRetMsg,false);
Put this code in Page Load.
This should work:
$('.myClass, .myOtherClass').removeClass('theclass');
You must add the multiple selectors all in the first argument to $(), otherwise you are giving jQuery a context in which to search, which is not what you want.
It's the same as you would do in CSS.
Latest Versions of mysql don't support DATEADD instead use the syntax
DATE_ADD(date,INTERVAL expr type)
To get the last 3 months data use,
DATE_ADD(NOW(),INTERVAL -90 DAY)
DATE_ADD(NOW(), INTERVAL -3 MONTH)
redirect_to new_user_path(:id => 1, :contact_id => 3, :name => 'suleman')
If for matching identical images ( same size/orientation )
// Compare two images by getting the L2 error (square-root of sum of squared error).
double getSimilarity( const Mat A, const Mat B ) {
if ( A.rows > 0 && A.rows == B.rows && A.cols > 0 && A.cols == B.cols ) {
// Calculate the L2 relative error between images.
double errorL2 = norm( A, B, CV_L2 );
// Convert to a reasonable scale, since L2 error is summed across all pixels of the image.
double similarity = errorL2 / (double)( A.rows * A.cols );
return similarity;
}
else {
//Images have a different size
return 100000000.0; // Return a bad value
}
According to pytest documentation, version 3 of pytest can temporary disable capture in a test:
def test_disabling_capturing(capsys):
print('this output is captured')
with capsys.disabled():
print('output not captured, going directly to sys.stdout')
print('this output is also captured')
//Off the cuff, Prototype style.
//Note, this is not optimal; there should be some basic partitioning and caching going on.
(function () {
var elements = [];
Element.register = function (element) {
for (var i=0; i<elements.length; i++) {
if (elements[i]==element) break;
}
elements.push(element);
if (arguments.length>1)
for (var i=0; i<arguments.length; i++)
Element.register(arguments[i]);
};
Element.collide = function () {
for (var outer=0; outer < elements.length; outer++) {
var e1 = Object.extend(
$(elements[outer]).positionedOffset(),
$(elements[outer]).getDimensions()
);
for (var inner=outer; inner<elements.length; innter++) {
var e2 = Object.extend(
$(elements[inner]).positionedOffset(),
$(elements[inner]).getDimensions()
);
if (
(e1.left+e1.width)>=e2.left && e1.left<=(e2.left+e2.width) &&
(e1.top+e1.height)>=e2.top && e1.top<=(e2.top+e2.height)
) {
$(elements[inner]).fire(':collision', {element: $(elements[outer])});
$(elements[outer]).fire(':collision', {element: $(elements[inner])});
}
}
}
};
})();
//Usage:
Element.register(myElementA);
Element.register(myElementB);
$(myElementA).observe(':collision', function (ev) {
console.log('Damn, '+ev.memo.element+', that hurt!');
});
//detect collisions every 100ms
setInterval(Element.collide, 100);
move.CompleteMove()
does not return a value (perhaps it just prints something). Any method that does not return a value returns None
, and you have assigned None
to self.values
.
Here is an example of this:
>>> def hello(x):
... print x*2
...
>>> hello('world')
worldworld
>>> y = hello('world')
worldworld
>>> y
>>>
You'll note y
doesn't print anything, because its None
(the only value that doesn't print anything on the interactive prompt).
Had a weird situation where I had a decimal variable, when serializing 55.50 it always sets default value mathematically as 55.5. But whereas, our client system is seriously expecting 55.50 for some reason and they definitely expected decimal. Thats when I had write the below helper, which always converts any decimal value padded to 2 digits with zeros instead of sending a string.
public static class DecimalExtensions
{
public static decimal WithTwoDecimalPoints(this decimal val)
{
return decimal.Parse(val.ToString("0.00"));
}
}
Usage should be
var sampleDecimalValueV1 = 2.5m;
Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());
decimal sampleDecimalValueV1 = 2;
Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());
Output:
2.50
2.00
I wrote this simple helper:
Handlebars.registerHelper('conditions', function (options) {
var data = this;
data.__check_conditions = true;
return options.fn(this);
});
Handlebars.registerHelper('next', function(conditional, options) {
if(conditional && this.__check_conditions) {
this.__check_conditions = false;
return options.fn(this);
} else {
return options.inverse(this);
}
});
It's something like Chain Of Responsibility pattern in Handlebars
Example:
{{#conditions}}
{{#next condition1}}
Hello 1!!!
{{/next}}
{{#next condition2}}
Hello 2!!!
{{/next}}
{{#next condition3}}
Hello 3!!!
{{/next}}
{{#next condition4}}
Hello 4!!!
{{/next}}
{{/conditions}}
It's not a else if but in some cases it may help you)
You can do:
#if MACRO0
//code...
#elif MACRO1
//code...
#endif
…where the identifier can be:
__linux__ Defined on Linux
__sun Defined on Solaris
__FreeBSD__ Defined on FreeBSD
__NetBSD__ Defined on NetBSD
__OpenBSD__ Defined on OpenBSD
__APPLE__ Defined on Mac OS X
__hpux Defined on HP-UX
__osf__ Defined on Tru64 UNIX (formerly DEC OSF1)
__sgi Defined on Irix
_AIX Defined on AIX
_WIN32 Defined on Windows
You can't svn:ignore a file that is already commited to repository.
So you must:
Good luck!
If the number matches than I am checking it's occur first time or not with help of "indexOf()" if the number matches first time then print and save into in a string so, that when the next time same number matches then it's won't print because due to "indexOf()" condition will be false.
class Intersection
{
public static void main(String[] args)
{
String s="";
int[] array1 = {1, 2, 5, 5, 8, 9, 7,2,3512451,4,4,5 ,10};
int[] array2 = {1, 0, 6, 15, 6, 5,4, 1,7, 0,5,4,5,2,3,8,5,3512451};
for (int i = 0; i < array1.length; i++)
{
for (int j = 0; j < array2.length; j++)
{
char c=(char)(array1[i]);
if(array1[i] == (array2[j])&&s.indexOf(c)==-1)
{
System.out.println("Common element is : "+(array1[i]));
s+=c;
}
}
}
}
}
It is privacy concern. It is recommended to disallow users to backup an app if it contains sensitive data. Having access to backup files (i.e. when android:allowBackup="true"
), it is possible to modify/read the content of an app even on a non-rooted device.
Solution - use android:allowBackup="false"
in the manifest file.
You can read this post to have more information: Hacking Android Apps Using Backup Techniques
If you are in a MySQL
shell, exit it by typing exit, which will return you to the command prompt.
Now start MySQL
by using exactly the following command:
sudo mysql -u root -p
If your username is something other than root, replace 'root' in the above command with your username:
sudo mysql -u <your-user-name> -p
It will then ask you the MySQL
account/password, and your MySQL
won't show any access privilege issue then on.
Not only heap memory. also increase perm size to resolve that exception in maven use these variables in environment variable.
variable name: MAVEN_OPTS
variable value: -Xmx512m -XX:MaxPermSize=256m
Example :
export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=500m"
There is a problem with every answer provided that can be summarized as "just add this magical incantation to the beginning of your script. See what you can do with just a line or two of code." They will not work in every possible situation!
For example, one such magical incantation uses __file__
. Unfortunately, if you package your script using cx_Freeze or you are using IDLE, this will result in an exception.
Another such magical incantation uses os.getcwd(). This will only work if you are running your script from the command prompt and the directory containing your script is the current working directory (that is you used the cd command to change into the directory prior to running the script). Eh gods! I hope I do not have to explain why this will not work if your Python script is in the PATH somewhere and you ran it by simply typing the name of your script file.
Fortunately, there is a magical incantation that will work in all the cases I have tested. Unfortunately, the magical incantation is more than just a line or two of code.
import inspect
import os
import sys
# Add script directory to sys.path.
# This is complicated due to the fact that __file__ is not always defined.
def GetScriptDirectory():
if hasattr(GetScriptDirectory, "dir"):
return GetScriptDirectory.dir
module_path = ""
try:
# The easy way. Just use __file__.
# Unfortunately, __file__ is not available when cx_Freeze is used or in IDLE.
module_path = __file__
except NameError:
if len(sys.argv) > 0 and len(sys.argv[0]) > 0 and os.path.isabs(sys.argv[0]):
module_path = sys.argv[0]
else:
module_path = os.path.abspath(inspect.getfile(GetScriptDirectory))
if not os.path.exists(module_path):
# If cx_Freeze is used the value of the module_path variable at this point is in the following format.
# {PathToExeFile}\{NameOfPythonSourceFile}. This makes it necessary to strip off the file name to get the correct
# path.
module_path = os.path.dirname(module_path)
GetScriptDirectory.dir = os.path.dirname(module_path)
return GetScriptDirectory.dir
sys.path.append(os.path.join(GetScriptDirectory(), "lib"))
print(GetScriptDirectory())
print(sys.path)
As you can see, this is no easy task!
Optimization of the accepted answer:
The accepted answer has some functioning problems, so I want to share my code that does not rely on urllib2:
import requests
from pandas import json_normalize
url = 'https://www.energidataservice.dk/proxy/api/datastore_search?resource_id=nordpoolmarket&limit=5'
response = requests.get(url)
dictr = response.json()
recs = dictr['result']['records']
df = json_normalize(recs)
print(df)
Output:
_id HourUTC HourDK ... ElbasAveragePriceEUR ElbasMaxPriceEUR ElbasMinPriceEUR
0 264028 2019-01-01T00:00:00+00:00 2019-01-01T01:00:00 ... NaN NaN NaN
1 138428 2017-09-03T15:00:00+00:00 2017-09-03T17:00:00 ... 33.28 33.4 32.0
2 138429 2017-09-03T16:00:00+00:00 2017-09-03T18:00:00 ... 35.20 35.7 34.9
3 138430 2017-09-03T17:00:00+00:00 2017-09-03T19:00:00 ... 37.50 37.8 37.3
4 138431 2017-09-03T18:00:00+00:00 2017-09-03T20:00:00 ... 39.65 42.9 35.3
.. ... ... ... ... ... ... ...
995 139290 2017-10-09T13:00:00+00:00 2017-10-09T15:00:00 ... 38.40 38.4 38.4
996 139291 2017-10-09T14:00:00+00:00 2017-10-09T16:00:00 ... 41.90 44.3 33.9
997 139292 2017-10-09T15:00:00+00:00 2017-10-09T17:00:00 ... 46.26 49.5 41.4
998 139293 2017-10-09T16:00:00+00:00 2017-10-09T18:00:00 ... 56.22 58.5 49.1
999 139294 2017-10-09T17:00:00+00:00 2017-10-09T19:00:00 ... 56.71 65.4 42.2
PS: API is for Danish electricity prices
It's also possible to get this error if you are running the test project using JUnit instead of Android JUnit. Naturally, the solution is just to change how you run it.
''' This code works for me, and is as simple as that.
Here I have taken the value of ip and I am trying to match it with regex.
ip="25.255.45.67"
op=re.match('(\d+).(\d+).(\d+).(\d+)',ip)
if ((int(op.group(1))<=255) and (int(op.group(2))<=255) and int(op.group(3))<=255) and (int(op.group(4))<=255)):
print("valid ip")
else:
print("Not valid")
Above condition checks if the value exceeds 255 for all the 4 octets then it is not a valid. But before applying the condition we have to convert them into integer since the value is in a string.
group(0) prints the matched output, Whereas group(1) prints the first matched value and here it is "25" and so on. '''
Use this command : (Jarsigner is in your Java bin folder goto java->jdk->bin path in cmd prompt)
$ jarsigner -verify my_signed.apk
If the .apk is signed properly, Jarsigner prints "jar verified"
Best practice is a real loaded term. I like a DbDataContext
style container like Dapper.Rainbow promotes. It allows you to couple the CommandTimeout
, transaction and other helpers.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using Dapper;
// to have a play, install Dapper.Rainbow from nuget
namespace TestDapper
{
class Program
{
// no decorations, base class, attributes, etc
class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime? LastPurchase { get; set; }
}
// container with all the tables
class MyDatabase : Database<MyDatabase>
{
public Table<Product> Products { get; set; }
}
static void Main(string[] args)
{
var cnn = new SqlConnection("Data Source=.;Initial Catalog=tempdb;Integrated Security=True");
cnn.Open();
var db = MyDatabase.Init(cnn, commandTimeout: 2);
try
{
db.Execute("waitfor delay '00:00:03'");
}
catch (Exception)
{
Console.WriteLine("yeah ... it timed out");
}
db.Execute("if object_id('Products') is not null drop table Products");
db.Execute(@"create table Products (
Id int identity(1,1) primary key,
Name varchar(20),
Description varchar(max),
LastPurchase datetime)");
int? productId = db.Products.Insert(new {Name="Hello", Description="Nothing" });
var product = db.Products.Get((int)productId);
product.Description = "untracked change";
// snapshotter tracks which fields change on the object
var s = Snapshotter.Start(product);
product.LastPurchase = DateTime.UtcNow;
product.Name += " World";
// run: update Products set LastPurchase = @utcNow, Name = @name where Id = @id
// note, this does not touch untracked columns
db.Products.Update(product.Id, s.Diff());
// reload
product = db.Products.Get(product.Id);
Console.WriteLine("id: {0} name: {1} desc: {2} last {3}", product.Id, product.Name, product.Description, product.LastPurchase);
// id: 1 name: Hello World desc: Nothing last 12/01/2012 5:49:34 AM
Console.WriteLine("deleted: {0}", db.Products.Delete(product.Id));
// deleted: True
Console.ReadKey();
}
}
}
With my library pyexcel
,
$ pip install pyexcel pyexcel-xlsx
you can do it in one command line:
from pyexcel.cookbook import merge_all_to_a_book
# import pyexcel.ext.xlsx # no longer required if you use pyexcel >= 0.2.2
import glob
merge_all_to_a_book(glob.glob("your_csv_directory/*.csv"), "output.xlsx")
Each csv will have its own sheet and the name will be their file name.
UltimateSAML SSO is an OASIS SAML v1.x and v2.0 specifications compliant .NET toolkit. It offers an elegant and easy way to add support for Single Sign-On and Single-Logout SAML to your ASP.NET, ASP.NET MVC, ASP.NET Core, Desktop, and Service applications. The lightweight library helps you provide SSO access to cloud and intranet websites using a single credentials entry.
The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.
The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete
to do so.
Update in 2017: Hey. This is a terrible answer. Don't use it. Back in the old days this type of jQuery use was common. And it probably worked back then. Just read it, realize it's terrible, then move on (or downvote or, whatever) to one of the other answers that are better for today's jQuery.
$("input[type=radio]").change(function(){
alert( $("input[type=radio][name="+ this.name + "]").val() );
});
I faced the same issue. I had missed the forms module import tag in the app.module.ts
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [BrowserModule,
FormsModule
],
You can use browscap-java to get browser's information.
For Example:
UserAgentParser parser = new UserAgentService().loadParser(Arrays.asList(BrowsCapField.BROWSER));
Capabilities capabilities = parser.parse(user_agent);
String browser = capabilities.getBrowser();
It is always preferred to use a virtual environment ,Create your virtual environment using :
python -m venv <name_of_virtualenv>
go to your environment directory and activate your environment using below command on windows:
env_name\Scripts\activate.bat
then simply use
pip install package_name
The regular expression:
^[^_]*_(.*)$
Then get the part between parenthesis. In perl:
my var = "3.04_somename.jpg";
$var =~ m/^[^_]*_(.*)$/;
my fileName = $1;
In Java:
String var = "3.04_somename.jpg";
String fileName = "";
Pattern pattern = Pattern.compile("^[^_]*_(.*)$");
Matcher matcher = pattern.matcher(var);
if (matcher.matches()) {
fileName = matcher.group(1);
}
...
Or try this one:
System.out.println("First Name: " + firstname + " Last Name: "+ lastname +".");
Good luck!
Almost every library I know defines a utility class called StringUtils
, StringUtil
or StringHelper
, and they usually include the method you are looking for.
My personal favorite is Apache Commons / Lang, where in the StringUtils class, you get both the
(The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only)
There are similar utility classes in Spring, Wicket and lots of other libs. If you don't use external libraries, you might want to introduce a StringUtils class in your own project.
Update: many years have passed, and these days I'd recommend using Guava's Strings.isNullOrEmpty(string)
method.
Get the id of the div
whose content you want to change then assign the text as below:
var myDiv = document.getElementById("divId");
myDiv.innerHTML = "Content To Show";
Not the best answer, but it's an option anyway:
Comment the given line in the web.config.
The answer is to use a JSONArray as well, and to dive "deep" into the tree structure:
JSONArray arr = new JSONArray();
arr.put (...); // a new JSONObject()
arr.put (...); // a new JSONObject()
JSONObject json = new JSONObject();
json.put ("aoColumnDefs",arr);
Using the code from my answer to a very similar question:
Sub DoSomething()
Dim Mainfram(4) As String
Dim cell As Excel.Range
Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"
For Each cell In Selection
If IsInArray(cell.Value, MainFram) Then
Row(cell.Row).Style = "Accent1"
End If
Next cell
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -- -f [email protected] -F "Elvis Presley"
or
echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -aFrom:"Elvis Presley<[email protected]>"
INSERT INTO tablename
(name, salary)
VALUES
('Bob', 1125),
('Jane', 1200),
('Frank', 1100),
('Susan', 1175),
('John', 1150)
ON DUPLICATE KEY UPDATE salary = VALUES(salary);
Note that your pod specs will remain, and are located at ~/.cocoapods/ . This directory may also need to be removed if you want a completely fresh install.
They can be removed using pod spec remove SPEC_NAME
then pod setup
It may help to do pod spec remove master
then pod setup
On my Mac, I wrote this code in my Terminal:
xxx-MacBook-Pro:~ xxx$ cd /Users/xxx/Documents/0_Software/adt20140702/sdk/platform-tools/
xxx-MacBook-Pro:platform-tools xxx$ ./adb kill-server
xxx-MacBook-Pro:platform-tools xxx$ ./adb start-server
- daemon not running. starting it now on port 5037 *
- daemon started successfully *
xxx-MacBook-Pro:platform-tools tuananh$
Hope this help.
Try the arithmetic-expression version of for
:
max=10
for (( i=2; i <= $max; ++i ))
do
echo "$i"
done
This is available in most versions of bash, and should be Bourne shell (sh) compatible also.
Both these will give you the first child node:
console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);
If you need the first child that is an element node then use:
console.log(parentElement.children[0]);
Edit
Ah, I see your problem now; parentElement
is an array.
If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0]
to dearray (yes, I made that word up) the element:
var parentElement = document.getElementsByClassName("uniqueClassName")[0];
If you have this setup
/app
/public/index.html
/media
Then this should get what you wanted
var express = require('express');
//var server = express.createServer();
// express.createServer() is deprecated.
var server = express(); // better instead
server.configure(function(){
server.use('/media', express.static(__dirname + '/media'));
server.use(express.static(__dirname + '/public'));
});
server.listen(3000);
The trick is leaving this line as last fallback
server.use(express.static(__dirname + '/public'));
As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.
For example this line shows that index.html is supported https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140
If you don't have any ordered column, you can use the physical id of each lines:
SELECT top 1 sys.fn_PhysLocFormatter(%%physloc%%) AS [File:Page:Slot],
T.*
FROM MyTable As T
order by sys.fn_PhysLocFormatter(%%physloc%%) DESC
You can also plot the timestamp, value pairs using pyplot.plot (after parsing them from their string representation). (Tested with matplotlib versions 1.2.0 and 1.3.1.)
Example:
import datetime
import random
import matplotlib.pyplot as plt
# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]
# plot
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()
plt.show()
Resulting image:
Here's the same as a scatter plot:
import datetime
import random
import matplotlib.pyplot as plt
# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]
# plot
plt.scatter(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()
plt.show()
Produces an image similar to this:
On your own system, try
install.packages("foo", dependencies=...)
with the dependencies=
argument is documented as
dependencies: logical indicating to also install uninstalled packages
which these packages depend on/link to/import/suggest (and so
on recursively). Not used if ‘repos = NULL’. Can also be a
character vector, a subset of ‘c("Depends", "Imports",
"LinkingTo", "Suggests", "Enhances")’.
Only supported if ‘lib’ is of length one (or missing), so it
is unambiguous where to install the dependent packages. If
this is not the case it is ignored, with a warning.
The default, ‘NA’, means ‘c("Depends", "Imports",
"LinkingTo")’.
‘TRUE’ means (as from R 2.15.0) to use ‘c("Depends",
"Imports", "LinkingTo", "Suggests")’ for ‘pkgs’ and
‘c("Depends", "Imports", "LinkingTo")’ for added
dependencies: this installs all the packages needed to run
‘pkgs’, their examples, tests and vignettes (if the package
author specified them correctly).
so you probably want a value TRUE
.
In your package, list what is needed in Depends:
, see the
Writing R Extensions manual which is pretty clear on this.
A likely possibility is that your browser reaches your web service through a proxy, and SoapUI is not configured to use that proxy. For example, I work in a corporate environment and while my IE and FireFox can access external websites, my SoapUI can only access internal web services.
The easy solution is to just open the WSDL in a browser, save it to a .xml file, and base your SoapUI project on that. This won't work if your WSDL relies on external XSDs that it can't get to, however.
I think this should do it..
Select
ProductName,
WeekNumber,
sum(sale)
from
(
SELECT
ProductName,
DATEDIFF(week, '2011-05-30', date) AS WeekNumber,
sale
FROM table
)
GROUP BY
ProductName,
WeekNumber
I don't think you can, the only other configuration alternative is to enumerate the paths that you want to be filtered, so instead of /*
you could add some for /this/*
and /that/*
etc, but that won't lead to a sufficient solution when you have alot of those paths.
What you can do is add a parameter to the filter providing an expression (like a regular expression) which is used to skip the filter functionality for the paths matched. The servlet container will still call your filter for those url's but you will have better control over the configuration.
Edit
Now that you mention you have no control over the filter, what you could do is either inherit from that filter calling super
methods in its methods except when the url path you want to skip is present and follow the filter chain like @BalusC proposed, or build a filter which instantiates your filter and delegates under the same circumstances. In both cases the filter parameters would include both the expression parameter you add and those of the filter you inherit from or delegate to.
The advantage of building a delegating filter (a wrapper) is that you can add the filter class of the wrapped filter as parameter and reuse it in other situations like this one.
ClassLoader.class.getResourceAsStream("/path/to/your/xml")
and make sure that your compile script is copying the xml file to where in your CLASSPATH.
I tried many ways but this works.
Sample code is availalbe in DBCC SHRINKFILE
USE DBName;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE DBName
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (DBName_log, 1); --File name SELECT * FROM sys.database_files; query to get the file name
GO
-- Reset the database recovery model.
ALTER DATABASE DBName
SET RECOVERY FULL;
GO
Here comes the perfect example:
https://laravel.com/docs/5.8/database#listening-for-query-events
Open app\Providers\AppServiceProvider.php and add the following to Boot() function:
DB::listen(function ($query) {
var_dump([
$query->sql,
$query->bindings,
$query->time
]);
});
So you don't need to put DB::enableQuerylog()
and DB::getQuerylog()
in every function.
js version, catches iPad too:
var is_mobile = /mobile|android/i.test (navigator.userAgent);
A pretty nice way to do this is to use SimpleDateFormat
I'll show you how:
SimpleDateFormat sdf = new SimpleDateFormat("d MMMM YYYY");
Date d = new Date();
sdf.format(d);
I see that you have the date in a variable:
sdf.format(variable_name);
Cheers.
Try setting the timeout value in your web service proxy class:
WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds
I love the answer from @Bert F but this is the way my brain sees it.
I have an X in my hand. If I want to write my X into a List, that List needs to be either a List of X or a List of things that my X can be upcast to as I write them in i.e. any superclass of X...
List<? super X>
If I get a List and I want to read an X out of that List, that better be a List of X or a List of things that can be upcast to X as I read them out, i.e. anything that extends X
List<? extends X>
Hope this helps.
var divss = 0;
$(function(){
$("#foo div").each(function(){
divss++;
});
console.log(divss);
});
<div id="foo">
<div id="bar" class="1"></div>
<div id="baz" class="1"></div>
<div id="bam" class="1"></div>
</div>
You can use your "git url" in 'https" URL format in the Jenkinsfile or wherever you want.
git url: 'https://github.com/jglick/simple-maven-project-with-tests.git'
It is better to use eager loading when it is possible, because it optimizes the performance of your application.
ex-:
Eager loading
var customers= _context.customers.Include(c=> c.membershipType).Tolist();
lazy loading
In model customer has to define
Public virtual string membershipType {get; set;}
So when querying lazy loading is much slower loading all the reference objects, but eager loading query and select only the object which are relevant.
You can open the file, go to 0 offset relative from the bottom of the file with
#define SEEKBOTTOM 2
fseek(handle, 0, SEEKBOTTOM)
the value returned from fseek is the size of the file.
I didn't code in C for a long time, but I think it should work.
You can try this
$('#select_id').select2({ minimumResultsForSearch: -1 });
it closes the search results box and then set control unvisible
You can check here in select2 document select2 documents
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
I would simply do this, which literally follows what your desired logic was:
df.groupby(['org']).mean().groupby(['cluster']).mean()
Initialize your now
variable.
time_t now = time(0); // Get the system time
The localtime
function is used to convert the time value in the passed time_t
to a struct tm
, it doesn't actually retrieve the system time.
joaquin's answer works, but has the side effect of removing ticks from the left side of the axes. To fix this, follow up tick_right()
with a call to set_ticks_position('both')
. A revised example:
from matplotlib import pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_ticks_position('both')
plt.plot([2,3,4,5])
plt.show()
The result is a plot with ticks on both sides, but tick labels on the right.
InnerHTML should be innerHTML:
document.getElementById('LblAboutMeCount').innerHTML = charsleft;
You should bind your checkLength
function to your textarea with jQuery rather than calling it inline and rather intrusively:
$(document).ready(function() {
$('textarea[name=text]').keypress(function(e) {
checkLength($(this),512,$('#LblTextCount'));
}).focus(function() {
checkLength($(this),512,$('#LblTextCount'));
});
});
You can neaten up checkLength by using more jQuery, and I wouldn't use 'object' as a formal parameter:
function checkLength(obj, maxlength, label) {
charsleft = (maxlength - obj.val().length);
// never allow to exceed the specified limit
if( charsleft < 0 ) {
obj.val(obj.val().substring(0, maxlength-1));
}
// I'm trying to set the value of charsleft into the label
label.text(charsleft);
$('#LblAboutMeCount').html(charsleft);
}
So if you apply the above, you can change your markup to:
<textarea name="text"></textarea>
In this example ordering adds no information - the COUNT of a set is the same whatever order it is in!
If you were selecting something that did depend on order, you would need to do one of the things the error message tells you - use TOP or FOR XML
There are plenty of answers here explaining what you could do (I use the different field name one) but the simple (and as-yet unstated) answer to your question is 'no' - you can't have a different text and value using just HTML.
Thanks to @IanRoberts, I had to use the normalize-space function on my nodes to check if they were empty.
<xsl:if test="((node/ABC!='') and (normalize-space(node/DEF)='') and (normalize-space(node/GHI)=''))">
This worked perfectly fine.
</xsl:if>
In case anyone else is looking for this... as of April 2013, you can still get the free Visual Studio edition of Crystal Reports from this web site: SAP Crystal Reports - Downloads (updated url).
It installs into Visual Studio 2010 or VS 2012, and you can edit and save RPT files with as much capability as the standard Crystal Reports editor.
jQuery .bind() has been deprecated. Use .on() instead
$(window).on("beforeunload", function() {
runBeforeClose();
});
You’re looking for urllib.parse.urlencode
import urllib.parse
params = {'username': 'administrator', 'password': 'xyz'}
encoded = urllib.parse.urlencode(params)
# Returns: 'username=administrator&password=xyz'
can this help?
select
(SELECT group_concat(DISTINCT a) FROM my_table) as a,
(SELECT group_concat(DISTINCT b) FROM my_table) as b,
(SELECT group_concat(DISTINCT c) FROM my_table) as c,
(SELECT group_concat(DISTINCT d) FROM my_table) as d
This is a specific issue for Windows Vista, 7, 8 (and presumably newer).
User Account Control (UAC) is a feature in Windows that can help you stay in control of your computer by informing you when a program makes a change that requires administrator-level permission. UAC works by adjusting the permission level of your user account.
This is applied mostly to C:\Program Files. You may have noticed sometimes, that some applications can see files in C:\Program Files that does not exist there. You know why? Windows now tend to have "C:\Program Files" folder customized for every user. For example, old applications store config files (like .ini) in the same folder where the executable files are stored. In the good old days all users had the same configurations for such apps. In nowadays Windows stores configs in the special folder tied to the user account. Thus, now different users may have different configs while application still think that config files are in the same folder with the executables.
XAMPP does not like to have different config for different users. In fact it is not a config file for XAMPP, it is folders where you keep your projects and databases. The idea of XAMPP is to make projects same for all users. This is a source of a conflict with Windows.
All you need is to avoid installing XAMPP into C:\Program Files. Thus XAMPP will always use the original files for all users and there would be no confusion.
I recommend to install XAMPP into the special folder in root directory like in C:\XAMPP. But before you choose the folder you need to click on this warning message.
If your dates are strings in a strict yyyy-mm-dd
format as shown in the question then your code will work as is without converting to date objects or numbers:
if(first > second){
...will do a lexographic (i.e., alphanumeric "dictionary order") string comparison - which will compare the first characters of each string, then the second characters of each string, etc. Which will give the result you want...
To append a string, just concatenate it with the +
sign.
E.g.
>>> a = "Hello, "
>>> b = "world"
>>> str = a + b
>>> print str
Hello, world
join
connects strings together with a separator. The separator is what you
place right before the join
. E.g.
>>> "-".join([a,b])
'Hello, -world'
Join takes a list of strings as a parameter.
But always look out in the console / log for messages. If you see a notification that your query could not be converted to SQL and will be evaluated locally then you may need to rewrite it.
Entity Framework 7 (now renamed to Entity Framework Core 1.0 / 2.0) does not yet support GroupBy()
for translation to GROUP BY
in generated SQL (even in the final 1.0 release it won't). Any grouping logic will run on the client side, which could cause a lot of data to be loaded.
Eventually code written like this will automagically start using GROUP BY, but for now you need to be very cautious if loading your whole un-grouped dataset into memory will cause performance issues.
For scenarios where this is a deal-breaker you will have to write the SQL by hand and execute it through EF.
If in doubt fire up Sql Profiler and see what is generated - which you should probably be doing anyway.
https://blogs.msdn.microsoft.com/dotnet/2016/05/16/announcing-entity-framework-core-rc2
Describe Formatted/Extended will show the data definition of the table in hive
hive> describe Formatted dbname.tablename;
I think the variable is available directly, rather than through env, when using Workflow plugin. Try:
node()
{
print "DEBUG: parameter foo = ${foo}"
}
Your json contains an array, but you're trying to parse it as an object.
This error occurs because objects must start with {
.
You have 2 options:
You can get rid of the ShopContainer
class and use Shop[]
instead
ShopContainer response = restTemplate.getForObject(
url, ShopContainer.class);
replace with
Shop[] response = restTemplate.getForObject(url, Shop[].class);
and then make your desired object from it.
You can change your server to return an object instead of a list
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(list);
replace with
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
new ShopContainer(list));
Sharer.php no longer allows you to customize. The page you share will be scraped for OG Tags and that data will be shared.
To properly customize, use FB.UI
which comes with the JS-SDK.
Simply call
print(unknownDataType.runtimeType)
on the data.
I got this error when trying to run my friend's solution file by visual studio 2010 after convert it to 2010 version. The fix is easy, I create new project, right click the solution to add existing .cpp and .h file from my friend's project. Then it work.
For those who came here looking for "how to get All input of POST" only
class Illuminate\Http\Request
extends from Symfony\Component\HttpFoundation\Request
which has two class variables that store request parameters.
public $query
- for GET parameters
public $request
- for POST parameters
Usage: To get a post data only
$request = Request::instance();
$request->request->all(); //Get all post requests
$request->request->get('my_param'); //Get a post parameter
Source here
EDIT
For Laravel >= 5.5, you can simply call $request->post()
or $request->post('my_param')
which internally calls $request->request->all()
or $request->request->get('my_param')
respectively.
More of an alternate solution, but all modern browsers send the domain cookies along with the connection, so using:
var authToken = 'R3YKZFKBVi';
document.cookie = 'X-Authorization=' + authToken + '; path=/';
var ws = new WebSocket(
'wss://localhost:9000/wss/'
);
End up with the request connection headers:
Cookie: X-Authorization=R3YKZFKBVi
ThisWorkbook.Worksheets("Master").Sheet1.Cells.Copy _
Destination:=newWorksheet.Cells
The above will copy the cells. If you really want to duplicate the entire sheet, then I'd go with @brettdj's answer.
If you have installed Google Toolbar for IE, may be you can face the same problem. Because, the toolbar capture the shortcut ctrl+Space.
Check if these free resources fit your need -
Something on the lines of this i belive should work.
parent.document.getElementById(iFrameID).style.height=framedPage.scrollHeight;
Load this with your body onload on the iframe content.
There are lots of operations in NumPy that could perhaps be put together to accomplish this. This will return indices of elements equal to item:
numpy.nonzero(array - item)
You could then take the first elements of the lists to get a single element.
Uploading a file to AWS s3 and sending the url in response for accessing the file.
Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency. check this npm module here.
When you are sending the request, make sure the headers, have Content-Type is multipart/form-data. We are sending the file location in the response, which will give the url, but if you want to access that url, make the bucket public or else you will not be able to access it.
upload.router.js
const express = require('express');
const router = express.Router();
const AWS = require('aws-sdk');
const multer = require('multer');
const storage = multer.memoryStorage()
const upload = multer({storage: storage});
const s3Client = new AWS.S3({
accessKeyId: 'your_access_key_id',
secretAccessKey: 'your_secret_access_id',
region :'ur region'
});
const uploadParams = {
Bucket: 'ur_bucket_name',
Key: '', // pass key
Body: null, // pass file body
};
router.post('/api/file/upload', upload.single("file"),(req,res) => {
const params = uploadParams;
uploadParams.Key = req.file.originalname;
uploadParams.Body = req.file.buffer;
s3Client.upload(params, (err, data) => {
if (err) {
res.status(500).json({error:"Error -> " + err});
}
res.json({message: 'File uploaded successfully','filename':
req.file.originalname, 'location': data.Location});
});
});
module.exports = router;
app.js
const express = require('express');
const app = express();
const router = require('./app/routers/upload.router.js');
app.use('/', router);
// Create a Server
const server = app.listen(8080, () => {
console.log("App listening at 8080");
})
Just to put one example here (system is in existingState
, and we want to find elements to remove (elements that are not in newState
but are present in existingState
) and elements to add (elements that are in newState
but are not present in existingState
) :
public class AddAndRemove {
static Set<Integer> existingState = Set.of(1,2,3,4,5);
static Set<Integer> newState = Set.of(0,5,2,11,3,99);
public static void main(String[] args) {
Set<Integer> add = new HashSet<>(newState);
add.removeAll(existingState);
System.out.println("Elements to add : " + add);
Set<Integer> remove = new HashSet<>(existingState);
remove.removeAll(newState);
System.out.println("Elements to remove : " + remove);
}
}
would output this as a result:
Elements to add : [0, 99, 11]
Elements to remove : [1, 4]
I had this issue as well, and the text-shadow
wasn't an option because the corners would look bad (unless I had many many shadows), and I didn't want any blur, therefore my only other option was to do the following: Have 2 divs, and for the background div, put a -webkit-text-stroke
on it, which then allows for as big of an outline as you like.
div {_x000D_
font-size: 200px;_x000D_
position: absolute;_x000D_
white-space: nowrap;_x000D_
}_x000D_
_x000D_
.front {_x000D_
color: blue;_x000D_
}_x000D_
_x000D_
.outline {_x000D_
-webkit-text-stroke: 30px red;_x000D_
user-select: none;_x000D_
}
_x000D_
<div class="outline">_x000D_
outline text_x000D_
</div>_x000D_
_x000D_
<div class="front">_x000D_
outline text_x000D_
</div>
_x000D_
Using this, I was able to achieve an outline, because the stroke-width
method was not an option if you want your text to remain legible with a very large outline (because with stroke-width
the outline will start inside the lettering which makes it not legible when the width gets larger than the letters.
Note: the reason I needed such a fat outline was I was emulating the street labels in "google maps" and I wanted a fat white halo around the text. This solution worked perfectly for me.
The solution I ended up choosing was MahApps.Metro (github), which (after using it on two pieces of software now) I consider an excellent UI kit (credit to Oliver Vogel for the suggestion).
It skins the application with very little effort required, and has adaptations of the standard Windows 8 controls. It's very robust.
A version is available on Nuget:
You can install MahApps.Metro via Nuget using the GUI (right click on your project, Manage Nuget References, search for ‘MahApps.Metro’) or via the console:
PM> Install-Package MahApps.Metro
It's also free -- even for commercial use.
I discovered that the Github version of MahApps.Metro is packed with controls and styles that aren't available in the current nuget version, including:
The github repository is very active with quite a bit of user contributions. I recommend checking it out.
Converting to a DATE
or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand
From that article:
DECLARE @dateVar datetime = '19700204';
-- Quickest when there is an index on t.[DateColumn],
-- because CONVERT can still use the index.
SELECT t.[DateColumn]
FROM MyTable t
WHERE = CONVERT(DATE, t.[DateColumn]) = CONVERT(DATE, @dateVar);
-- Quicker when there is no index on t.[DateColumn]
DECLARE @dateEnd datetime = DATEADD(DAY, 1, @dateVar);
SELECT t.[DateColumn]
FROM MyTable t
WHERE t.[DateColumn] >= @dateVar AND
t.[DateColumn] < @dateEnd;
Also from that article: using BETWEEN
, DATEDIFF
or CONVERT(CHAR(8)...
are all slower.
I find it easier using this formula
=IF(B2<>"",TEXT(ROW(A1),"IR-0000"),"")
Need to paste this formula at A2, that means when you are encoding data at B cell the A cell will automatically input the serial code and when there's no data the cell will stay blank....you can change the "IR" to any first letter code you want to be placed in your row.
Hope it helps
Just a suggestion,in your code instead of using let newData = prevState.data
you could use spread which is introduced in ES6 that is you can uselet newData = ...prevState.data
for copying array
Three dots ... represents Spread Operators or Rest Parameters,
It allows an array expression or string or anything which can be iterating to be expanded in places where zero or more arguments for function calls or elements for array are expected.
Additionally you can delete item from array with following
onRemovePerson: function(index) {
this.setState((prevState) => ({
data: [...prevState.data.slice(0,index), ...prevState.data.slice(index+1)]
}))
}
Hope this contributes!!
Please correct me if I'm wrong.`
public static void main(String[] args) {
Scanner na = new Scanner(System.in);
System.out.println("Please enter the number of contacts: ");
int num = na.nextInt();
String[] contactName = new String[num];
String[] contactPhone = new String[num];
String[] contactAdd1 = new String[num];
String[] contactAdd2 = new String[num];
Scanner input = new Scanner(System.in);
for (int i = 0; i < num; i++) {
System.out.println("Enter contacts name: " + (i+1));
contactName[i] = input.nextLine();
System.out.println("Enter contacts addressline1: " + (i+1));
contactAdd1[i] = input.nextLine();
System.out.println("Enter contacts addressline2: " + (i+1));
contactAdd2[i] = input.nextLine();
System.out.println("Enter contact phone number: " + (i+1));
contactPhone[i] = input.nextLine();
}
for (int i = 0; i < num; i++) {
System.out.println("Contact Name No." + (i+1) + " is "+contactName[i]);
System.out.println("First Contacts Address No." + (i+1) + " is "+contactAdd1[i]);
System.out.println("Second Contacts Address No." + (i+1) + " is "+contactAdd2[i]);
System.out.println("Contact Phone Number No." + (i+1) + " is "+contactPhone[i]);
}
}
`
As per Oracle Glossary :
SID is a unique name for an Oracle database instance. ---> To switch between Oracle databases, users must specify the desired SID <---. The SID is included in the CONNECT DATA parts of the connect descriptors in a TNSNAMES.ORA file, and in the definition of the network listener in the LISTENER.ORA file. Also known as System ID. Oracle Service Name may be anything descriptive like "MyOracleServiceORCL". In Windows, You can your Service Name running as a service under Windows Services.
You should use SID in TNSNAMES.ORA as a better approach.
Fairly simple process I am using SCSS obviously but you don't have to as it's just CSS in the end!
<span class="menu">Menu</span>
.menu {
position: relative;
text-decoration: none;
font-weight: 400;
color: blue;
transition: all .35s ease;
&::before {
content: "";
position: absolute;
width: 100%;
height: 2px;
bottom: 0;
left: 0;
background-color: yellow;
visibility: hidden;
-webkit-transform: scaleX(0);
transform: scaleX(0);
-webkit-transition: all 0.3s ease-in-out 0s;
transition: all 0.3s ease-in-out 0s;
}
&:hover {
color: yellow;
&::before {
visibility: visible;
-webkit-transform: scaleX(1);
transform: scaleX(1);
}
}
}
You can create bitmap with captured image as below:
Bitmap bitmap = Bitmap.createScaledBitmap(capturedImage, width, height, true);
Here you can specify width and height of the bitmap that you want to set to your ImageView. The height and width you can set according to the screen dpi of the device also, by reading the screen dpi of different devices programmatically.
Gulp doesn't offer any kind of util for that, but you can use one of the many command args parsers. I like yargs
. Should be:
var argv = require('yargs').argv;
gulp.task('my-task', function() {
return gulp.src(argv.a == 1 ? options.SCSS_SOURCE : options.OTHER_SOURCE)
.pipe(sass({style:'nested'}))
.pipe(autoprefixer('last 10 version'))
.pipe(concat('style.css'))
.pipe(gulp.dest(options.SCSS_DEST));
});
You can also combine it with gulp-if
to conditionally pipe the stream, very useful for dev vs. prod building:
var argv = require('yargs').argv,
gulpif = require('gulp-if'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify');
gulp.task('my-js-task', function() {
gulp.src('src/**/*.js')
.pipe(concat('out.js'))
.pipe(gulpif(argv.production, uglify()))
.pipe(gulpif(argv.production, rename({suffix: '.min'})))
.pipe(gulp.dest('dist/'));
});
And call with gulp my-js-task
or gulp my-js-task --production
.
from
is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`
.
Personally, I wouldn't bother; I'd just rename the column.
PS. as pointed out in the comments, to
is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at drupal.org maintain a list of reserved words in SQL.
strchr for searching a char from start (strrchr from the end):
char str[] = "This is a sample string";
if (strchr(str, 'h') != NULL) {
/* h is in str */
}
Serial sends data 8 bits at a time, that translates to 1 byte and 1 byte means 1 character.
You need to implement your own method that can read characters into a buffer until some sentinel is reached. The convention is to send a message like 12431\n
indicating one line.
So what you need to do is to implement a buffer that will store X number of characters and as soon as you reach that \n
, perform your operation on the line and proceed to read the next line into the buffer.
Note you will have to take care of buffer overflow cases i.e. when a line is received that is longer than your buffer etc...
EDIT
import serial
ser = serial.Serial(
port='COM5',\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
print("connected to: " + ser.portstr)
#this will store the line
line = []
while True:
for c in ser.read():
line.append(c)
if c == '\n':
print("Line: " + ''.join(line))
line = []
break
ser.close()