First,
sudo apt-get install libusb-1.0-0-dev
updatedb && locate libusb.h.
Second, replace <libusb.h>
with <libusb-1.0/libusb.h>
.
update:
don't need to change any file.just add this to your Makefile.
`pkg-config libusb-1.0 --libs --cflags`
its result is that -I/usr/include/libusb-1.0 -lusb-1.0
When I run your code, I get the following output for example.
<usb.Device object at 0xef38c0>
Device: 001
idVendor: 7531 (0x1d6b)
idProduct: 1 (0x0001)
Manufacturer: 3
Serial: 1
Product: 2
Noteworthy are that a) I have usb.Device
objects whereas you have usb.legacy.Device
objects, and b) I have device filenames.
Each usb.Bus
has a dirname
field and each usb.Device
has the filename. As you can see, the filename is something like 001
, and so is the dirname. You can combine these to get the bus file. For dirname=001
and filname=001
, it should be something like /dev/bus/usb/001/001.
You should first, though figure out what this "usb.legacy" situation is. I'm running the latest version and I don't even have a legacy
sub-module.
Finally, you should use the idVendor
and idProduct
fields to uniquely identify the device when it's plugged in.
My solution:
complete
)/*global define */
define(['angular', './my-module'], function(angular, directives) {
'use strict';
directives.directive('polimerBinding', ['$compile', function($compile) {
return {
restrict: 'A',
scope: {
method:'&polimerBinding'
},
link : function(scope, element, attrs) {
var el = element[0];
var expressionHandler = scope.method();
var siemEvent = attrs['polimerEvent'];
if (!siemEvent) {
siemEvent = 'complete';
}
el.addEventListener(siemEvent, function (e, options) {
expressionHandler(e.detail);
})
}
};
}]);
});
<dom-module id="search">
<template>
<h3>Search</h3>
<div class="input-group">
<textarea placeholder="search by expression (eg. temperature>100)"
rows="10" cols="100" value="{{text::input}}"></textarea>
<p>
<button id="button" class="btn input-group__addon">Search</button>
</p>
</div>
</template>
<script>
Polymer({
is: 'search',
properties: {
text: {
type: String,
notify: true
},
},
regularSearch: function(e) {
console.log(this.range);
this.fire('complete', {'text': this.text});
},
listeners: {
'button.click': 'regularSearch',
}
});
</script>
</dom-module>
<search id="search" polimer-binding="searchData"
siem-event="complete" range="{{range}}"></siem-search>
searchData
is the control function
$scope.searchData = function(searchObject) {
alert('searchData '+ searchObject.text + ' ' + searchObject.range);
}
Maybe your remote repo is in the branch which you want to push. You can try to checkout another branch in your remote machine. I did this, than these error disappeared, and I pushed success to my remote repo. Notice that I use ssh to connect my own server instead of github.com.
First, you can switch on an enum
in Java. I'm guessing you intended to say you can’t, but you can. char
s have a set range of values, so it's easy to compare. Strings can be anything.
A switch
statement is usually implemented as a jump table (branch table) in the underlying compilation, which is only possible with a finite set of values. C# can switch on strings, but it causes a performance decrease because a jump table cannot be used.
Java 7 and later supports String
switches with the same characteristics.
You can always add the "!" into your float-options. This way, latex tries really hard to place the figure where you want it (I mostly use [h!tb]), stretching the normal rules of type-setting.
I have found another solution:
Use the float-package. This way you can place the figures where you want them to be.
One of the latest XAMPP releases (XAMPP for Windows v5.6.11 (PHP 5.6.11) for sure, probably some earlier versions too) does not have the Control Panel with the "Svc" checkbox that allows to install Apache and MySQL as a service.
Go to your XAMPP/Apache directory instead (typically C:/xampp/apache
) and run apache_installservice.bat as an administrator. There is also apache_uninstallservice.bat for uninstall.
To run MySQL as a service. Do it the same way - the location is xampp/mysql
and batch files are: mysql_installservice.bat for service installation and mysql_uninstallservice.bat for removing the MySQL service.
You can check if they were installed or not by going to services manager window (press Windows + R and type: services.msc) and check if you have Apache service (I had Apache2.4) running and set to startup automatically. The MySQL service name is just: mysql.
Probably the bast way is to build a custom method mixing a combination of regex and small look up on your file system (to see the drives, for example)
I found that the direct cause for the error in my case was:
this makes sense since the error is stating that there is an invalid option for language.
but, this was working fine before - so it must've been selected. what changed? turns out a member on my team upgraded to vs 2017, while i was still using 2015. after he made changes to the project, the language version was changed and i received that change over source control. but the version selected was not available to my version of vs, so it was blank - hence the error. after selecting a value in the language drop down (i chose default), a new error popped up. the new error was causing a build failure on any lines of code which used the newer version of c#. i changed the code to perform the same functions, but with my c# version syntax and problem solved.
so while the direct cause of the error was indeed an invalid selection of Language Version, the root cause was due to different vs/c# versions conflicting.
My jquery method, this one puts the footer at the bottom of the page if the page content is less than the window height, or just puts the footer after the content otherwise:
Also, keeping the code in it's own enclosure before other code will reduce the time it takes to reposition the footer.
(function() {
$('.footer').css('position', $(document).height() > $(window).height() ? "inherit" : "fixed");
})();
I had a similar problem at work, I was rewriting our image transform endpoint and I wanted to check that the new version was producing the same or nearly the same output as the old version. So I wrote this:
https://github.com/nicolashahn/diffimg
Which operates on images of the same size, and at a per-pixel level, measures the difference in values at each channel: R, G, B(, A), takes the average difference of those channels, and then averages the difference over all pixels, and returns a ratio.
For example, with a 10x10 image of white pixels, and the same image but one pixel has changed to red, the difference at that pixel is 1/3 or 0.33... (RGB 0,0,0 vs 255,0,0) and at all other pixels is 0. With 100 pixels total, 0.33.../100 = a ~0.33% difference in image.
I believe this would work perfectly for OP's project (I realize this is a very old post now, but posting for future StackOverflowers who also want to compare images in python).
Its just a sample of how to post Json data and get Json data to/from a Rest API in BIDS 2008 using System.Net.WebRequest and without using newtonsoft. This is just a sample code and definitely can be fine tuned (well tested and it works and serves my test purpose like a charm). Its just to give you an Idea. I wanted this thread but couldn't find hence posting this.These were my major sources from where I pulled this. Link 1 and Link 2
Code that works(unit tested)
//Get Example
var httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
var username = "usernameForYourApi";
var password = "passwordForYourApi";
var bytes = Encoding.UTF8.GetBytes(username + ":" + password);
httpWebRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
var httpResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Dts.Events.FireInformation(3, "result from readng stream", result, "", 0, ref fireagain);
}
//Post Example
var httpWebRequestPost = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
httpWebRequestPost.ContentType = "application/json";
httpWebRequestPost.Method = "POST";
bytes = Encoding.UTF8.GetBytes(username + ":" + password);
httpWebRequestPost.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
//POST DATA newtonsoft didnt worked with BIDS 2008 in this test package
//json https://stackoverflow.com/questions/6201529/how-do-i-turn-a-c-sharp-object-into-a-json-string-in-net
// fill File model with some test data
CSharpComplexClass fileModel = new CSharpComplexClass();
fileModel.CarrierID = 2;
fileModel.InvoiceFileDate = DateTime.Now;
fileModel.EntryMethodID = EntryMethod.Manual;
fileModel.InvoiceFileStatusID = FileStatus.NeedsReview;
fileModel.CreateUserID = "37f18f01-da45-4d7c-a586-97a0277440ef";
string json = new JavaScriptSerializer().Serialize(fileModel);
Dts.Events.FireInformation(3, "reached json", json, "", 0, ref fireagain);
byte[] byteArray = Encoding.UTF8.GetBytes(json);
httpWebRequestPost.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = httpWebRequestPost.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = httpWebRequestPost.GetResponse();
// Display the status.
//Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Dts.Events.FireInformation(3, "Display the status", ((HttpWebResponse)response).StatusDescription, "", 0, ref fireagain);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
Dts.Events.FireInformation(3, "responseFromServer ", responseFromServer, "", 0, ref fireagain);
References in my test script task inside BIDS 2008(having SP1 and 3.5 framework)
If you really want a matrix, you might be better off using numpy
. Matrix operations in numpy
most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros
function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:
>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):
numpy.arange(25).reshape((5, 5)) # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.ones((5, 5)) # initialize with ones
numpy
provides a matrix
type as well, but it is no longer recommended for any use, and may be removed from numpy
in the future.
Just follow the steps in this URl: CLICK HERE
I know this is kinda old, but...
ES2015:
var toHHMMSS = (secs) => {
var sec_num = parseInt(secs, 10)
var hours = Math.floor(sec_num / 3600)
var minutes = Math.floor(sec_num / 60) % 60
var seconds = sec_num % 60
return [hours,minutes,seconds]
.map(v => v < 10 ? "0" + v : v)
.filter((v,i) => v !== "00" || i > 0)
.join(":")
}
It will output:
toHHMMSS(129600) // 36:00:00
toHHMMSS(13545) // 03:45:45
toHHMMSS(180) // 03:00
toHHMMSS(18) // 00:18
There is also the excellent markupsafe package.
>>> from markupsafe import Markup, escape
>>> escape("<script>alert(document.cookie);</script>")
Markup(u'<script>alert(document.cookie);</script>')
The markupsafe
package is well engineered, and probably the most versatile and Pythonic way to go about escaping, IMHO, because:
Markup
) is a class derived from unicode (i.e. isinstance(escape('str'), unicode) == True
__html__
property) and template overloads (__html_format__
).There is an easier solution to this problem.
You just need to add a t
to the mode so it becomes wt
. This causes Python to open the file as a text file and not binary. Then everything will just work.
The complete program becomes this:
plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wt") as outfile:
outfile.write(plaintext)
I'm new to Xcode, so it took me a few hours to figure out the issue in order to load xls file. I followed through most of the sample codes up there and none of them solves the error Xcode shown.
The solution I found was that we need to specify the 'Add to targets:' tick the project to add, when we import the xls file into Xcode by drag and drop into Project -> Supporting Files.
Use $("input").attr("maxlength", 4)
if you're using jQuery version < 1.6
and $("input").prop("maxLength", 4)
if you are using jQuery version 1.6+.
The one way is by using webservice, simply write a webservice method in PHP or any other language . And From your android app by using http client request and response , you can hit the web service method which will return whatever you want.
For PHP You can create a webservice like this. Assuming below we have a php file in the server. And the route of the file is yourdomain.com/api.php
if(isset($_GET['api_call'])){
switch($_GET['api_call']){
case 'userlogin':
//perform your userlogin task here
break;
}
}
Now you can use Volley or Retrofit to send a network request to the above PHP Script and then, actually the php script will handle the database operation.
In this case the PHP script is called a RESTful API.
You can learn all the operation at MySQL from this tutorial. Android MySQL Tutorial to Perform CRUD.
In my case, I disabled "Block TCP 445" on Windows Defender Firewall with Advanced Security and it worked. Then enabled it again after setting shared drives on Docker.
This is how I do it:
df_ext = pd.DataFrame(index=pd.date_range(df.index[-1], periods=8, closed='right'))
df2 = pd.concat([df, df_ext], axis=0, sort=True)
df2["forecast"] = df2["some column"].shift(7)
Basically I am generating an empty dataframe with the desired index and then just concatenate them together. But I would really like to see this as a standard feature in pandas so I have proposed an enhancement to pandas.
You can create a custom serializer inline in the mixin. Then annotate a field with it. See example below that appends " - something else " to lang field. This is kind of hackish - if your serializer requires something like a repository or anything injected by spring, this is going to be a problem. Probably best to use a custom deserializer/serializer instead of a mixin.
package com.test;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.test.Argument;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//Serialize only fields explicitly mentioned by this mixin.
@JsonAutoDetect(
fieldVisibility = Visibility.NONE,
setterVisibility = Visibility.NONE,
getterVisibility = Visibility.NONE,
isGetterVisibility = Visibility.NONE,
creatorVisibility = Visibility.NONE
)
@JsonPropertyOrder({"lang", "name", "value"})
public abstract class V2ArgumentMixin {
@JsonProperty("name")
private String name;
@JsonSerialize(using = LangCustomSerializer.class, as=String.class)
@JsonProperty("lang")
private String lang;
@JsonProperty("value")
private Object value;
public static class LangCustomSerializer extends JsonSerializer<String> {
@Override
public void serialize(String value,
JsonGenerator jsonGenerator,
SerializerProvider serializerProvider)
throws IOException, JsonProcessingException {
jsonGenerator.writeObject(value.toString() + " - something else");
}
}
}
You could try posting multipart content from the client like this:
using (var httpClient = new HttpClient())
{
var uri = new Uri("http://example.com/api/controller"));
using (var formData = new MultipartFormDataContent())
{
//add content to form data
formData.Add(new StringContent(JsonConvert.SerializeObject(content)), "Content");
//add config to form data
formData.Add(new StringContent(JsonConvert.SerializeObject(config)), "Config");
var response = httpClient.PostAsync(uri, formData);
response.Wait();
if (!response.Result.IsSuccessStatusCode)
{
//error handling code goes here
}
}
}
On the server side you could read the the content like this:
public async Task<HttpResponseMessage> Post()
{
//make sure the post we have contains multi-part data
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
//read data
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
//declare backup file summary and file data vars
var content = new Content();
var config = new Config();
//iterate over contents to get Content and Config
foreach (var requestContents in provider.Contents)
{
if (requestContents.Headers.ContentDisposition.Name == "Content")
{
content = JsonConvert.DeserializeObject<Content>(requestContents.ReadAsStringAsync().Result);
}
else if (requestContents.Headers.ContentDisposition.Name == "Config")
{
config = JsonConvert.DeserializeObject<Config>(requestContents.ReadAsStringAsync().Result);
}
}
//do something here with the content and config and set success flag
var success = true;
//indicate to caller if this was successful
HttpResponseMessage result = Request.CreateResponse(success ? HttpStatusCode.OK : HttpStatusCode.InternalServerError, success);
return result;
}
}
string.Format("{0:yyyy-MM-ddTHH:mm:ss.FFFZ}", DateTime.UtcNow)
returns 2017-02-10T08:12:39.483Z
i have tried upgrading node-gyp:
sudo npm install -g node-gyp
It worked for me.
I find the solution here, I hope it can help.
char vIn = 'A';
String vOut = Character.toString(vIn);
For these types of conversion, I have site bookmarked called https://www.converttypes.com/ It helps me quickly get the conversion code for most of the languages I use.
You can run the sleep command before your ExecStart with ExecStartPre :
[Service]
ExecStartPre=/bin/sleep 30
Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :
</body>
<script>require('../script/viewLog.js')</script>
after :
<script>require('../script/viewLog.js')</script>
</body>
Do you checks that file is uploaded ok ? Maybe you exceeded max_post_size, or max_upload_filesize. When login using FileZilla you are copying files as you, when uploading by PHP wiritng this file is from user that runs apache (for exaplme www-data), try to put chmod 755 for images.
There are a few ways to do it. If I want to read and write binary I usually use open()
, read()
, write()
, close()
. Which are completely different than doing a byte at a time. You work with integer file descriptors instead of FILE * variables. fileno will get an integer descriptor from a FILE * BTW. You read a buffer full of data, say 32k bytes at once. The buffer is really an array which you can read from really fast because it's in memory. And reading and writing many bytes at once is faster than one at a time. It's called a blockread in Pascal I think, but read() is the C equivalent.
I looked but I don't have any examples handy. OK, these aren't ideal because they also are doing stuff with JPEG images. Here's a read, you probably only care about the part from open() to close(). fbuf is the array to read into, sb.st_size is the file size in bytes from a stat() call.
fd = open(MASKFNAME,O_RDONLY);
if (fd != -1) {
read(fd,fbuf,sb.st_size);
close(fd);
splitmask(fbuf,(uint32_t)sb.st_size); // look at lines, etc
have_mask = 1;
}
Here's a write: (here pix is the byte array, jwidth and jheight are the JPEG width and height so for RGB color we write height * width * 3 color bytes). It's the # of bytes to write.
void simpdump(uint8_t *pix, char *nm) { // makes a raw aka .data file
int sdfd;
sdfd = open(nm,O_WRONLY | O_CREAT);
if (sdfd == -1) {
printf("bad open\n");
exit(-1);
}
printf("width: %i height: %i\n",jwidth,jheight); // to the console
write(sdfd,pix,(jwidth*jheight*3));
close(sdfd);
}
Look at man 2 open, also read, write, close. Also this old-style jpeg example.c: https://github.com/LuaDist/libjpeg/blob/master/example.c I'm reading and writing an entire image at once here. But they're binary reads and writes of bytes, just a lot at once.
"But when I try to read from a file it is not outputting correctly." Hmmm. If you read a number 65 that's (decimal) ASCII for an A. Maybe you should look at man ascii too. If you want a 1 that's ASCII 0x31. A char variable is a tiny 8-bit integer really, if you do a printf as a %i you get the ASCII value, if you do a %c you get the character. Do %x for hexadecimal. All from the same number between 0 and 255.
I had a similar issue except my problem was silly - I had 2 instances of the built-in web server running under 2 different ports AND I had my project -> properties -> web -> "Start URL" pointing to a fixed port but the web app was not actually running under that port. So my browser was being redirected to the "Start URL" which referred to 1539 but the code/debug instance was running under port 50803.
I changed the builtin web server to run under a fixed port and adjusted my "Start URL" to use that port as well. project -> properties -> web -> "Servers" section -> "Use Visual Studio Development Server" -> specific port
Class org.apache.commons.lang3.CharEncoding.UTF_8
is deprecated after Java 7 introduced java.nio.charset.StandardCharsets
The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBody annotation.
Then try the following:
@RequestMapping(value = "/patientdetails", method = RequestMethod.POST,consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public @ResponseBody List<PatientProfileDto> getPatientDetails(
PatientProfileDto name) {
List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
list = service.getPatient(name);
return list;
}
Note that removed the annotation @RequestBody
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];
$.each(arrofobject, function(index, val) {
console.log(val.category);
});
I had a similar issue with generated strongly typed datasets, the full error message was:
Could not find an implementation of the query pattern for source type 'MyApp.InvcHeadDataTable'. 'Where' not found. Consider explicitly specifying the type of the range variable 'row'.
From my code:
var x =
from row in ds.InvcHead
where row.Company == Session.CompanyID
select row;
So I did as it suggested and explicitly specified the type:
var x =
from MyApp.InvcHeadRow row in ds.InvcHead
where row.Company == Session.CompanyID
select row;
Which worked a treat.
.innerText
doesnt work in Firefox.
.innerHTML
works in both the browsers.
If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest
android:exported="true"
Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.
finish();
The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class
in the code, so compile will fail.
I searched on the web and found something like this below, and it works well.
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);
You can also use the setClassName method:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();
You can also pass the values from one app to another app :
Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
launchIntent.putExtra("AppID", "MY-CHILD-APP1");
launchIntent.putExtra("UserID", "MY-APP");
launchIntent.putExtra("Password", "MY-PASSWORD");
startActivity(launchIntent);
finish();
} else {
Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}
This works well for me, for several buttons, with different image width and different title length :
Subclass UIButton
override func layoutSubviews() {
super.layoutSubviews()
if let image = imageView?.image {
let margin = 30 - image.size.width / 2
let titleRect = titleRectForContentRect(bounds)
let titleOffset = (bounds.width - titleRect.width - image.size.width - margin) / 2
contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
imageEdgeInsets = UIEdgeInsetsMake(0, margin, 0, 0)
titleEdgeInsets = UIEdgeInsetsMake(0, (bounds.width - titleRect.width - image.size.width - margin) / 2, 0, 0)
}
}
You can add PresentationCore.dll more conveniently by editing the project file. Add the following code into your csproj file:
<ItemGroup>
<FrameworkReference Include="Microsoft.WindowsDesktop.App" />
</ItemGroup>
In your solution explorer, you now should see this framework listed, now. With that, you then can also refer to the classes provided by PresentationCore.dll.
A method has already been devised, however this way you don't need a temp file.
for /f "delims=" %%i in ('command') do set output=%%i
However, I'm sure this has its own exceptions and limitations.
You can also use the xattr
command as in Stack Overflow question How do I remove the "extended attributes" on a file in Mac OS X?.
Just remove the com.apple.quarantine
attribute. It works even if you don't have an administrator account, which can be a plus. After that, the app isn't considered "downloaded" and is therefore not blocked.
Using the highlighted/checked answer above worked for me... here's a little insight. I cheated a little on getting the URL, but basically I'm defining the URL in the Javascript, and then setting it via the jquery answer from above:
<select id="select" onChange="window.location.href=this.value">
<option value="">Select a task </option>
<option value="http://127.0.0.1:5000/choose_form/1">Task 1</option>
<option value="http://127.0.0.1:5000/choose_form/2">Task 2</option>
<option value="http://127.0.0.1:5000/choose_form/3">Task 3</option>
<option value="http://127.0.0.1:5000/choose_form/4">Task 4</option>
<option value="http://127.0.0.1:5000/choose_form/5">Task 5</option>
<option value="http://127.0.0.1:5000/choose_form/6">Task 6</option>
<option value="http://127.0.0.1:5000/choose_form/7">Task 7</option>
<option value="http://127.0.0.1:5000/choose_form/8">Task 8</option>
</select>
<script>
var pathArray = window.location.pathname.split( '/' );
var selectedItem = "http://127.0.0.1:5000/" + pathArray[1] + "/" + pathArray[2];
var trimmedItem = selectedItem.trim();
$("#select").val(trimmedItem);
</script>
You should wrap your recursive function call into a
setTimeout
,setImmediate
or process.nextTick
function to give node.js the chance to clear the stack. If you don't do that and there are many loops without any real async function call or if you do not wait for the callback, your RangeError: Maximum call stack size exceeded
will be inevitable.
There are many articles concerning "Potential Async Loop". Here is one.
Now some more example code:
// ANTI-PATTERN
// THIS WILL CRASH
var condition = false, // potential means "maybe never"
max = 1000000;
function potAsyncLoop( i, resume ) {
if( i < max ) {
if( condition ) {
someAsyncFunc( function( err, result ) {
potAsyncLoop( i+1, callback );
});
} else {
// this will crash after some rounds with
// "stack exceed", because control is never given back
// to the browser
// -> no GC and browser "dead" ... "VERY BAD"
potAsyncLoop( i+1, resume );
}
} else {
resume();
}
}
potAsyncLoop( 0, function() {
// code after the loop
...
});
This is right:
var condition = false, // potential means "maybe never"
max = 1000000;
function potAsyncLoop( i, resume ) {
if( i < max ) {
if( condition ) {
someAsyncFunc( function( err, result ) {
potAsyncLoop( i+1, callback );
});
} else {
// Now the browser gets the chance to clear the stack
// after every round by getting the control back.
// Afterwards the loop continues
setTimeout( function() {
potAsyncLoop( i+1, resume );
}, 0 );
}
} else {
resume();
}
}
potAsyncLoop( 0, function() {
// code after the loop
...
});
Now your loop may become too slow, because we loose a little time (one browser roundtrip) per round. But you do not have to call setTimeout
in every round. Normally it is o.k. to do it every 1000th time. But this may differ depending on your stack size:
var condition = false, // potential means "maybe never"
max = 1000000;
function potAsyncLoop( i, resume ) {
if( i < max ) {
if( condition ) {
someAsyncFunc( function( err, result ) {
potAsyncLoop( i+1, callback );
});
} else {
if( i % 1000 === 0 ) {
setTimeout( function() {
potAsyncLoop( i+1, resume );
}, 0 );
} else {
potAsyncLoop( i+1, resume );
}
}
} else {
resume();
}
}
potAsyncLoop( 0, function() {
// code after the loop
...
});
Chrome DevTools, Safari Inspector and Firebug support getEventListeners(node).
string path = @"E:\AppServ\Example.txt";
File.AppendAllLines(path, new [] { "The very first line!" });
See also File.AppendAllText(). AppendAllLines will add a newline to each line without having to put it there yourself.
Both methods will create the file if it doesn't exist so you don't have to.
For today's Date
$(document).ready(function() {
$('#textboxname').datepicker();
$('#textboxname').datepicker('setDate', 'today');});
I just want to add to what others have already stated:
To make sure that the custom error class shows up properly in the stack trace, you need to set the custom error class's prototype's name property to the custom error class's name property. This is what I mean:
CustomError.prototype = Error.prototype;
CustomError.prototype.name = 'CustomError';
So the full example would be:
var CustomError = function(message) {
var err = new Error(message);
err.name = 'CustomError';
this.name = err.name;
this.message = err.message;
//check if there is a stack property supported in browser
if (err.stack) {
this.stack = err.stack;
}
//we should define how our toString function works as this will be used internally
//by the browser's stack trace generation function
this.toString = function() {
return this.name + ': ' + this.message;
};
};
CustomError.prototype = new Error();
CustomError.prototype.name = 'CustomError';
When all is said and done, you throw your new exception and it looks like this (I lazily tried this in the chrome dev tools):
CustomError: Stuff Happened. GASP!
at Error.CustomError (<anonymous>:3:19)
at <anonymous>:2:7
at Object.InjectedScript._evaluateOn (<anonymous>:603:39)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:562:52)
at Object.InjectedScript.evaluate (<anonymous>:481:21)
nice usage of java.io.FileFilter
as seen on https://stackoverflow.com/a/286001/146745
File fl = new File(dir);
File[] files = fl.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
});
In the absence of more detailed info:
using(var dbContext = new dbDataContext())
{
var data = dbContext.SomeTable.SingleOrDefault(row => row.id == requiredId);
if(data != null)
{
data.SomeField = newValue;
}
dbContext.SubmitChanges();
}
Always try to log in using those credentials with SQL Management Studio. This might reveal some more details that you don't get at runtime in your code. I had checked the SQL + Windows authentication, restarted the server but still no luck. After trying to log in using SQL Management, I got this prompt:
Somehow the password had expired although the login was created just minutes before. Anyway, new password set, connection string updated and all's fine.
With the design support library you can now change them in the xml:
To change the color of the TabLayout indicator:
app:tabIndicatorColor="@color/color"
To change the height of the TabLayout indicator:
app:tabIndicatorHeight="4dp"
This is in answer to your question...
I'd also like to know how to make it open up in Sublime Text 2 instead
For Windows:
git config --global core.editor "'C:/Program Files/Sublime Text 2/sublime_text.exe'"
Check that the path for sublime_text.exe
is correct and adjust if needed.
For Mac/Linux:
git config --global core.editor "subl -n -w"
If you get an error message such as:
error: There was a problem with the editor 'subl -n -w'.
Create the alias for subl
sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl
Again check that the path matches for your machine.
For Sublime Text simply save cmd S
and close the window cmd W
to return to git.
For variables, specifies that the type of the variable that is being declared will be automatically deduced from its initializer. For functions, specifies that the return type is a trailing return type or will be deduced from its return statements (since C++14).
Syntax
auto variable initializer (1) (since C++11)
auto function -> return type (2) (since C++11)
auto function (3) (since C++14)
decltype(auto) variable initializer (4) (since C++14)
decltype(auto) function (5) (since C++14)
auto :: (6) (concepts TS)
cv(optional) auto ref(optional) parameter (7) (since C++14)
Explanation
1) When declaring variables in block scope, in namespace scope, in initialization statements of for loops, etc., the keyword auto may be used as the type specifier.
Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto using the rules for template argument deduction from a function call (see template argument deduction#Other contexts for details). The keyword auto may be accompanied by modifiers, such as const or &, which will participate in the type deduction. For example, given const auto& i = expr;
, the type of i is exactly the type of the argument u in an imaginary template template<class U> void f(const U& u)
if the function call f(expr)
was compiled. Therefore, auto&& may be deduced either as an lvalue reference or rvalue reference according to the initializer, which is used in range-based for loop.
If auto is used to declare multiple variables, the deduced types must match. For example, the declaration auto i = 0, d = 0.0;
is ill-formed, while the declaration auto i = 0, *p = &i;
is well-formed and the auto is deduced as int.
2) In a function declaration that uses the trailing return type syntax, the keyword auto does not perform automatic type detection. It only serves as a part of the syntax.
3) In a function declaration that does not use the trailing return type syntax, the keyword auto indicates that the return type will be deduced from the operand of its return statement using the rules for template argument deduction.
4) If the declared type of the variable is decltype(auto), the keyword auto is replaced with the expression (or expression list) of its initializer, and the actual type is deduced using the rules for decltype.
5) If the return type of the function is declared decltype(auto), the keyword auto is replaced with the operand of its return statement, and the actual return type is deduced using the rules for decltype.
6) A nested-name-specifier of the form auto:: is a placeholder that is replaced by a class or enumeration type following the rules for constrained type placeholder deduction.
7) A parameter declaration in a lambda expression. (since C++14) A function parameter declaration. (concepts TS)
Notes
Until C++11, auto had the semantic of a storage duration specifier.
Mixing auto variables and functions in one declaration, as in auto f() -> int, i = 0;
is not allowed.
For more info : http://en.cppreference.com/w/cpp/language/auto
JOIN t2 ON (t2.id = t1.id AND t2.date = t1.date)
Can't you use VBA code to do the copy from excel and paste into SSMS operations?
@thebjorn has given a good answer. But if you want more options, you can try OpenCV, SimpleCV.
using SimpleCV (not supported in python3.x):
from SimpleCV import Image, Camera
cam = Camera()
img = cam.getImage()
img.save("filename.jpg")
using OpenCV:
from cv2 import *
# initialize the camera
cam = VideoCapture(0) # 0 -> index of camera
s, img = cam.read()
if s: # frame captured without any errors
namedWindow("cam-test",CV_WINDOW_AUTOSIZE)
imshow("cam-test",img)
waitKey(0)
destroyWindow("cam-test")
imwrite("filename.jpg",img) #save image
using pygame:
import pygame
import pygame.camera
pygame.camera.init()
pygame.camera.list_cameras() #Camera detected or not
cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
img = cam.get_image()
pygame.image.save(img,"filename.jpg")
Install OpenCV:
install python-opencv bindings, numpy
Install SimpleCV:
install python-opencv, pygame, numpy, scipy, simplecv
get latest version of SimpleCV
Install pygame:
install pygame
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?foo=bar';
window.history.pushState({path:newurl},'',newurl);
I found a solution that works for hiding the grid lines in a Line chart.
Set the gridLines
color to be the same as the div's background color.
var options = {
scales: {
xAxes: [{
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}],
yAxes: [{
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}]
}
}
or use
var options = {
scales: {
xAxes: [{
gridLines: {
display:false
}
}],
yAxes: [{
gridLines: {
display:false
}
}]
}
}
You can also use ddms for logcat logs where just giving search of the app name you will all info but you have to select Info instead of verbose or other options. check this below image.
If you don't wan't to use ng-model there is ng-value
you can try.
Here's the fiddle for this: http://jsfiddle.net/Rg9sG/1/
The presence of the n
option attached to the -k5
causes the global -r
option to be ignored for that field. You have to specify both n
and r
at the same level (globally or locally).
sort -t $'\t' -k5,5rn
or
sort -rn -t $'\t' -k5,5
In neither case is the "syntax malformed". It's the semantics that are wrong. Hence, IMHO a 400 is inappropriate. Instead, it would be appropriate to return a 200 along with some kind of error object such as { "error": { "message": "Unknown request keyword" } }
or whatever.
Consider the client processing path(s). An error in syntax (e.g. invalid JSON) is an error in the logic of the program, in other words a bug of some sort, and should be handled accordingly, in a way similar to a 403, say; in other words, something bad has gone wrong.
An error in a parameter value, on the other hand, is an error of semantics, perhaps due to say poorly validated user input. It is not an HTTP error (although I suppose it could be a 422). The processing path would be different.
For instance, in jQuery, I would prefer not to have to write a single error handler that deals with both things like 500 and some app-specific semantic error. Other frameworks, Ember for one, also treat HTTP errors like 400s and 500s identically as big fat failures, requiring the programmer to detect what's going on and branch depending on whether it's a "real" error or not.
For Oracle, I highly recommend the free Oracle SQL Developer
http://www.oracle.com/technology/products/database/sql_developer/index.html
The doucmentation states it also works with non-oracle databases - i've never tried that feature myself, but I do know that it works really well with Oracle
foreach (var data in dynObj.quizlist)
{
foreach (var data1 in data.QUIZ.QPROP)
{
Response.Write("Name" + ":" + data1.name + "<br>");
Response.Write("Intro" + ":" + data1.intro + "<br>");
Response.Write("Timeopen" + ":" + data1.timeopen + "<br>");
Response.Write("Timeclose" + ":" + data1.timeclose + "<br>");
Response.Write("Timelimit" + ":" + data1.timelimit + "<br>");
Response.Write("Noofques" + ":" + data1.noofques + "<br>");
foreach (var queprop in data1.QUESTION.QUEPROP)
{
Response.Write("Questiontext" + ":" + queprop.questiontext + "<br>");
Response.Write("Mark" + ":" + queprop.mark + "<br>");
}
}
}
The JAX-WS way for basic authentication is
Service s = new Service();
Port port = s.getPort();
BindingProvider prov = (BindingProvider)port;
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "myusername");
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "mypassword");
port.call();
I was going to go with Jason's answer but I noticed that in My version of Xcode (4.3.3) I couldn't do that. so after a bit of research I found they had recently changed the class methods and removed all the old ones. so here's how I had to do it:
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setMaximumFractionDigits:2];
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.342]]);
As said on most of the previous comments, the solution is to add
<item name="colorControlNormal">@color/white</item>
to your app theme.
But confirm that you don´t have another theme defined in your Toolbar element on your layout.
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
The following works in Python 2.6, 2.7, and 3.2:
import os
import sys
buf_arg = 0
if sys.version_info[0] == 3:
os.environ['PYTHONUNBUFFERED'] = '1'
buf_arg = 1
sys.stdout = os.fdopen(sys.stdout.fileno(), 'a+', buf_arg)
sys.stderr = os.fdopen(sys.stderr.fileno(), 'a+', buf_arg)
It is not too surprising: the execution plan for the tiny insert is computed once, and then reused 1000 times. Parsing and preparing the plan is quick, because it has only four values to del with. A 1000-row plan, on the other hand, needs to deal with 4000 values (or 4000 parameters if you parameterized your C# tests). This could easily eat up the time savings you gain by eliminating 999 roundtrips to SQL Server, especially if your network is not overly slow.
Follow the below steps:
Select body > form-data and do same as shown in the image.
Now in your Django view.py
def post(self, request, *args, **kwargs): image = request.FILES["image"] data = json.loads(request.data['data']) ... return Response(...)
There is the latest techniques to communicate fragment to activity without any interface follow the steps Step 1- Add the dependency in gradle
implementation 'androidx.fragment:fragment:1.3.0-rc01'
And this is less
@primarycolor: #ffffff;
@width: 800px;
body{
width: @width;
color: @primarycolor;
.content{
width: @width;
background:@primarycolor;
}
}
If you want one element with the corresponding one you could do
Enumerable.Range(0, List1.Count).All(x => List1[x] == List2[x]);
That will return true if every item is equal to the corresponding one on the second list
If that's almost but not quite what you want it would help if you elaborated more.
Try do something like this (the problem was that you trying to use MyBook.Worksheets
, but MyBook
is not a Workbook
object, but string
, containing workbook name. I've added new varible Set WB = ActiveWorkbook
, so you can use WB.Worksheets
instead MyBook.Worksheets
):
Sub NewWBandPasteSpecialALLSheets()
MyBook = ActiveWorkbook.Name ' Get name of this book
Workbooks.Add ' Open a new workbook
NewBook = ActiveWorkbook.Name ' Save name of new book
Workbooks(MyBook).Activate ' Back to original book
Set WB = ActiveWorkbook
Dim SH As Worksheet
For Each SH In WB.Worksheets
SH.Range("WholePrintArea").Copy
Workbooks(NewBook).Activate
With SH.Range("A1")
.PasteSpecial (xlPasteColumnWidths)
.PasteSpecial (xlFormats)
.PasteSpecial (xlValues)
End With
Next
End Sub
But your code doesn't do what you want: it doesen't copy something to a new WB. So, the code below do it for you:
Sub NewWBandPasteSpecialALLSheets()
Dim wb As Workbook
Dim wbNew As Workbook
Dim sh As Worksheet
Dim shNew As Worksheet
Set wb = ThisWorkbook
Workbooks.Add ' Open a new workbook
Set wbNew = ActiveWorkbook
On Error Resume Next
For Each sh In wb.Worksheets
sh.Range("WholePrintArea").Copy
'add new sheet into new workbook with the same name
With wbNew.Worksheets
Set shNew = Nothing
Set shNew = .Item(sh.Name)
If shNew Is Nothing Then
.Add After:=.Item(.Count)
.Item(.Count).Name = sh.Name
Set shNew = .Item(.Count)
End If
End With
With shNew.Range("A1")
.PasteSpecial (xlPasteColumnWidths)
.PasteSpecial (xlFormats)
.PasteSpecial (xlValues)
End With
Next
End Sub
attr_accessor
is (as @pst stated) just a method. What it does is create more methods for you.
So this code here:
class Foo
attr_accessor :bar
end
is equivalent to this code:
class Foo
def bar
@bar
end
def bar=( new_value )
@bar = new_value
end
end
You can write this sort of method yourself in Ruby:
class Module
def var( method_name )
inst_variable_name = "@#{method_name}".to_sym
define_method method_name do
instance_variable_get inst_variable_name
end
define_method "#{method_name}=" do |new_value|
instance_variable_set inst_variable_name, new_value
end
end
end
class Foo
var :bar
end
f = Foo.new
p f.bar #=> nil
f.bar = 42
p f.bar #=> 42
Here is a solution using sponge (from the moreutils package):
head -n -1 foo.txt | sponge foo.txt
Summary of solutions:
If you want a fast solution for large files, use the efficient tail or dd approach.
If you want something easy to extend/tweak and portable, use the redirect and move approach.
If you want something easy to extend/tweak, the file is not too large, portability (i.e., depending on moreutils
package) is not an issue, and you are a fan of square pants, consider the sponge approach.
A nice benefit of the sponge approach, compared to "redirect and move" approaches, is that sponge preserves file permissions.
Sponge uses considerably more RAM compared to the "redirect and move" approach. This gains a bit of speed (only about 20%), but if you're interested in speed the "efficient tail" and dd approaches are the way to go.
When analysing a Galaxy Ace 2.2 in a hex editor. The hex seemed to point to the device using FAT16 as its file system. I thought this unusual. However Fat 16 is compatible with the Linux kernel.
You can use Apache Commons Configuration library. The best part of this is, it won't even mess up the properties file and keeps it intact (even comments).
PropertiesConfiguration conf = new PropertiesConfiguration("propFile.properties");
conf.setProperty("key", "value");
conf.save();
I was also trying to use the [FromBody], however, I was trying to populate a string variable because the input will be changing and I just need to pass it along to a backend service but this was always null
Post([FromBody]string Input])
So I changed the method signature to use a dynamic class and then convert that to string
Post(dynamic DynamicClass)
{
string Input = JsonConvert.SerializeObject(DynamicClass);
This works well.
As an alternative option, if you are not married to the idea of migrations, there is a compelling gem for ActiveRecord which will handle the name changes automatically for you, Datamapper style. All you do is change the column name in your model (and make sure you put Model.auto_upgrade! at the bottom of your model.rb) and viola! Database is updated on the fly.
https://github.com/DAddYE/mini_record
Note: You will need to nuke db/schema.rb to prevent conflicts
Still in beta phases and obviously not for everyone but still a compelling choice (I am currently using it in two non-trivial production apps with no issues)
We should rather use Javascript.
<button href="images/car.jpg" id="myButton">
Here is the Button to be clicked
</button>
<script>
$(document).ready(function(){
document.getElementById("myButton").click();
});
</script>
You can put a middleware at the last position that throws a NotFound
error,
or even renders the 404 page directly:
app.use(function(req,res){
res.status(404).render('404.jade');
});
I found its work by restarting my phone :)
If it were me, I'd put the EXE file in the root directory (C:) and see if it works like that. If so, it's probably the (already mentioned) spaces in the directory name. If not, it may be some environment variables.
Also, try to check you stderr (using an earlier answer by int3):
import subprocess
process = subprocess.Popen(["C:/Documents and Settings/flow_model/flow.exe"], \
stderr = subprocess.PIPE)
if process.stderr:
print process.stderr.readlines()
The code might not be entirely correct as I usually don't use Popen or Windows, but should give the idea. It might well be that the error message is on the error stream.
str
is text representation in bytes, unicode
is text representation in characters.
You decode text from bytes to unicode and encode a unicode into bytes with some encoding.
That is:
>>> 'abc'.decode('utf-8') # str to unicode
u'abc'
>>> u'abc'.encode('utf-8') # unicode to str
'abc'
UPD Sep 2020: The answer was written when Python 2 was mostly used. In Python 3, str
was renamed to bytes
, and unicode
was renamed to str
.
>>> b'abc'.decode('utf-8') # bytes to str
'abc'
>>> 'abc'.encode('utf-8'). # str to bytes
b'abc'
The right way to do this is use git-remote-dropbox: https://github.com/anishathalye/git-remote-dropbox
Creating your own bare repo in Dropbox causes a lot of problems. Anish (the creator of the library) explains it best:
The root cause of these problems is that the Dropbox desktop client is designed for syncing files, not Git repositories. Without special handling for Git repositories, it doesn’t maintain the same guarantees as Git. Operations on the remote repository are no longer atomic, and concurrent operations or unlucky timing with synchronization can result in a corrupted repository.
Traditional Git remotes run code on the server side to make this work properly, but we can’t do that.
Solution: It is possible to solve this properly. It is possible to use Git with Dropbox and have the same safety and consistency guarantees as a traditional Git remote, even when there are multiple users and concurrent operations!
For a user, it’s as simple as using git-remote-dropbox, a Git remote helper that acts as a transparent bidirectional bridge between Git and Dropbox and maintains all the guarantees of a traditional Git remote. It’s even safe to use with shared folders, so it can be used for collaboration (yay unlimited private repos with unlimited collaborators!).
With the remote helper, it’s possible to use Dropbox as a Git remote and continue using all the regular Git commands like git clone, git pull, and git push, and everything will just work as expected.
I think you're looking for something like "URL encoding" - encoding a URL so that it's "safe" to use on the web:
Here's a reference for that. If you don't want any special characters, just remove any that require URL encoding:
The quickest approach is through two books:
1990 version of An Introduction to Compiling Techniques, a First Course using ANSI C, LeX, and YaCC by JP Bennett - a perfect balance of example code, parsing theory and design- it contains a complete compiler written in C, lex and yacc for a simple grammar
Dragon Book (older version) - mostly a detailed reference for the features not covered in the former book
Each numeric type has its own value. See TypeCode enum definition: https://docs.microsoft.com/en-us/dotnet/api/system.typecode?view=netframework-4.8 Based on this info, all your numeric type-values are in the range from 5 to 15. This means, you can write the condition-check like this:
$typeValue = $x.getTypeCode().value__
if ($typeValue -ge 5 -and $typeValue -le 15) {"x has a numeric type!"}
The main (very interesting) difference for me is that:
"string" & Null
-> "string"
while
"string" + Null
-> Null
But that's probably more useful in database apps like Access.
The major concern here is that the collections don't keep the type in the definition. The types are only available in runtime. I came up with a function to test complex collections (it has one constraint though).
Check if the object is an instance of a generic collection. In order to represent a collection,
false
instanceof
evaluationList
or Set
, the type of the list comes next e.g. {List, Integer} for List<Integer>
Map
, the key and value types come next e.g. {Map, String, Integer} for Map<String, Integer>
More complex use cases could be generated using the same rules. For example in order to represent List<Map<String, GenericRecord>>
, it can be called as
Map<String, Integer> map = new HashMap<>();
map.put("S1", 1);
map.put("S2", 2);
List<Map<String, Integer> obj = new ArrayList<>();
obj.add(map);
isInstanceOfGenericCollection(obj, List.class, List.class, Map.class, String.class, GenericRecord.class);
Note that this implementation doesn't support nested types in the Map. Hence, the type of key and value should be a class and not a collection. But it shouldn't be hard to add it.
public static boolean isInstanceOfGenericCollection(Object object, Class<?>... classes) {
if (classes.length == 0) return false;
if (classes.length == 1) return classes[0].isInstance(object);
if (classes[0].equals(List.class))
return object instanceof List && ((List<?>) object).stream().allMatch(item -> isInstanceOfGenericCollection(item, Arrays.copyOfRange(classes, 1, classes.length)));
if (classes[0].equals(Set.class))
return object instanceof Set && ((Set<?>) object).stream().allMatch(item -> isInstanceOfGenericCollection(item, Arrays.copyOfRange(classes, 1, classes.length)));
if (classes[0].equals(Map.class))
return object instanceof Map &&
((Map<?, ?>) object).keySet().stream().allMatch(classes[classes.length - 2]::isInstance) &&
((Map<?, ?>) object).values().stream().allMatch(classes[classes.length - 1]::isInstance);
return false;
}
When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.
But there are more important differences on the receiving side of things. When the receiver does a recv
(or read
) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.
Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.
I agree with above answers, the best way to get country from ip address is Maxmind.
If you want to write code in java, you might want to use i.e. geoip-api-1.2.10.jar and geoIP dat files (GeoIPCity.dat), which can be found via google.
Following code may be useful for you to get almost all information related to location, I am also using the same code.
public static String getGeoDetailsUsingMaxmind(String ipAddress, String desiredValue)
{
Location getLocation;
String returnString = "";
try
{
String geoIPCity_datFile = System.getenv("AUTOMATION_HOME").concat("/tpt/GeoIP/GeoIPCity.dat");
LookupService isp = new LookupService(geoIPCity_datFile);
getLocation = isp.getLocation(ipAddress);
isp.close();
//Getting all location details
if(desiredValue.equalsIgnoreCase("latitude") || desiredValue.equalsIgnoreCase("lat"))
{
returnString = String.valueOf(getLocation.latitude);
}
else if(desiredValue.equalsIgnoreCase("longitude") || desiredValue.equalsIgnoreCase("lon"))
{
returnString = String.valueOf(getLocation.longitude);
}
else if(desiredValue.equalsIgnoreCase("countrycode") || desiredValue.equalsIgnoreCase("country"))
{
returnString = getLocation.countryCode;
}
else if(desiredValue.equalsIgnoreCase("countryname"))
{
returnString = getLocation.countryName;
}
else if(desiredValue.equalsIgnoreCase("region"))
{
returnString = getLocation.region;
}
else if(desiredValue.equalsIgnoreCase("metro"))
{
returnString = String.valueOf(getLocation.metro_code);
}
else if(desiredValue.equalsIgnoreCase("city"))
{
returnString = getLocation.city;
}
else if(desiredValue.equalsIgnoreCase("zip") || desiredValue.equalsIgnoreCase("postalcode"))
{
returnString = getLocation.postalCode;
}
else
{
returnString = "";
System.out.println("There is no value found for parameter: "+desiredValue);
}
System.out.println("Value of: "+desiredValue + " is: "+returnString + " for ip address: "+ipAddress);
}
catch (Exception e)
{
System.out.println("Exception occured while getting details from max mind. " + e);
}
finally
{
return returnString;
}
}
You can use too
style="overflow-y: scroll; height:150px; width: auto;"
It's works for me
1) Run Visual Studio Installer
2) Click More on your Installed version and select Repair
3) Restart
Worked on Visual Studio 2017 Community
The solution depends on the answer to the question - are all the parameters going to be the same type and if so will each be treated the same?
If the parameters are not the same type or more importantly are not going to be treated the same then you should use method overloading:
public class MyClass
{
public void doSomething(int i)
{
...
}
public void doSomething(int i, String s)
{
...
}
public void doSomething(int i, String s, boolean b)
{
...
}
}
If however each parameter is the same type and will be treated in the same way then you can use the variable args feature in Java:
public MyClass
{
public void doSomething(int... integers)
{
for (int i : integers)
{
...
}
}
}
Obviously when using variable args you can access each arg by its index but I would advise against this as in most cases it hints at a problem in your design. Likewise, if you find yourself doing type checks as you iterate over the arguments then your design needs a review.
Just use
File.Copy(filepath, "\\\\192.168.1.28\\Files");
A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.
The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.
You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!
If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"
If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.
All I'm getting from that is
_internal
I get the route name from inside a controller with $this->getRequest()->get('_route').
Even the code tuxedo25 suggested returns _internal
This code is executed in what was called a 'Component' in Symfony 1.X; Not a page's controller but part of a page which needs some logic.
The equivalent code in Symfony 1.X is: sfContext::getInstance()->getRouting()->getCurrentRouteName();
For anyone else finding this - its worth noting that you can set the key value in the input name. Thanks to the answer in POSTing Form Fields with same Name Attribute you also can interplay strings or integers without quoting.
The answers assume that you don't mind the key value coming back for PHP however you can set name=[yourval]
(string or int) which then allows you to refer to an existing record.
To insert into only one column, use only one piece of data:
INSERT INTO Data ( Col1 ) VALUES
('Hello World');
Alternatively, to insert multiple records, separate the inserts:
INSERT INTO Data ( Col1 ) VALUES
('Hello'),
('World');
Some additional advice for Windows(10) users:
The correct way to open Jupyter notebook with new data limit from the Anaconda Prompt on my own Windows 10 PC is:
(base) C:\Users\mobarget\Google Drive\Jupyter Notebook>jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10
Its very easy to change in XCode 8, enter the app name in the "Display Name" field in Project Target -> General Identity section.
Changed the
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API">
function(){
myMap()
}
</script>
and made it
<script type="text/javascript">
function(){
myMap()
}
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API"></script>
It worked :)
for latest Jquery. Simply:
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
Mutexes have ownership, unlike semaphores. Although any thread, within the scope of a mutex, can get an unlocked mutex and lock access to the same critical section of code,only the thread that locked a mutex should unlock it.
A simple change in Num2 class like this:
super().__init__(num)
It works in python3.
class Num:
def __init__(self,num):
self.n1 = num
class Num2(Num):
def __init__(self,num):
super().__init__(num)
self.n2 = num*2
def show(self):
print (self.n1,self.n2)
mynumber = Num2(8)
mynumber.show()
You can explicitly specify the return type of a lambda by using -> Type
after the arguments list:
[]() -> Type { }
However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.
Answering this old question is pretty pointless, but there is a simple answer that speaks to the nature of Javascript. Objects in Javascript are inherently hash tables. We can use this to get a hash of unique keys:
var o = {}; array.map(function(v){ o[v.age] = 1; });
Then we can reduce the hash to an array of unique values:
var a2 = []; for (k in o){ a2.push(k); }
That is all you need. The array a2 contains just the unique ages.
For Swift :
self.imageViews.contentMode = UIViewContentMode.ScaleToFill
funtion isEmpty(o,i)
{
for(i in o)
{
return!1
}
return!0
}
After investigating lots of alternatives, I have come across another approach, suitable for the API 2.0 version.
(VB.NET is my favorite, sooo...)
Public Async Function APIPut_Response(ID as Integer, MyWidget as Widget) as Task(Of HttpResponseMessage)
Dim DesiredContent as HttpContent = New StringContent(JsonConvert.SerializeObject(MyWidget))
Return Await APIClient.PutAsync(String.Format("api/widget/{0}", ID), DesiredContent)
End Function
Good luck! For me this worked out (in the end!).
Regards, Peter
Selecting all the text you wish to format and pressing CtrlK, CtrlF shortcut applies the indenting and space formatting.
As specified in the Formatting pane (of the language being used) in the Text Editor section of the Options dialog.
See VS Shortcuts for more.
const
always modifies the thing that comes before it (to the left of it), EXCEPT when it's the first thing in a type declaration, where it modifies the thing that comes after it (to the right of it).
So these two are the same:
int const *i1;
const int *i2;
they define pointers to a const int
. You can change where i1
and i2
points, but you can't change the value they point at.
This:
int *const i3 = (int*) 0x12345678;
defines a const
pointer to an integer and initializes it to point at memory location 12345678. You can change the int
value at address 12345678, but you can't change the address that i3
points to.
Important: Version 1.0 of the reCAPTCHA API is no longer supported, please upgrade to Version 2.0.
You can use grecaptcha.reset(); to reset the captcha.
Source : https://developers.google.com/recaptcha/docs/verify#api-request
Kotlin Solution :
private fun locationEnabled() : Boolean {
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
}
SERIOUS DISCLAIMER
This solution has a serious security flaw. Please use at your own risk.
Have a look at the comments on this post, and look at all the answers to this question.
OK, I had to go to the customer premises and found a solution. I:
Then I opened the JAWS application without any warning. This is a little bit cumbersome, but much cheaper than buying a signed certificate!
For multiple shell commands, I ignores the failures by adding:
set +e
commands
true
If you don't want to make it final, you can always just make it a global variable.
The simple solution using geom_abline
:
geom_abline(slope = coef(data.lm)[[2]], intercept = coef(data.lm)[[1]])
Where data.lm
is an lm
object, and coef(data.lm)
looks something like this:
> coef(data.lm)
(Intercept) DepDelay
-2.006045 1.025109
The numeric indexing assumes that (Intercept)
is listed first, which is the case if the model includes an intercept. If you have some other linear model object, just plug in the slope and intercept values similarly.
Here is Oliver Steele's image of how it all fits together:
I had the same problem several times - just rebooting solves this.
SELECT *
FROM mytable
ORDER BY
column1 DESC, column2 ASC
We have the Proxy set on company level.
After disabling proxy in Internet Explorer this issue was solved (looks like it is then disabled on 'system' level), so all other browsers will pick this change too.
Now I can issue MVN commands from CMD prompt and I have no problem while e.g.
"Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-webapp/1.0/maven-archetype-webapp-1.0.pom"
...that was causing 'Build failure'
Disabling proxy in IE needs to be done on daily basis in our case, because on each system start it gets set
In bash echo
without quotes remove carriage returns, tabs and multiple spaces
echo $(cat file)
The problem was caused by not setting the CUDA_VISIBLE_DEVICES
variable within the shell correctly.
To specify CUDA device 1
for example, you would set the CUDA_VISIBLE_DEVICES
using
export CUDA_VISIBLE_DEVICES=1
or
CUDA_VISIBLE_DEVICES=1 ./cuda_executable
The former sets the variable for the life of the current shell, the latter only for the lifespan of that particular executable invocation.
If you want to specify more than one device, use
export CUDA_VISIBLE_DEVICES=0,1
or
CUDA_VISIBLE_DEVICES=0,1 ./cuda_executable
Qberticus's answer is good, but one useful detail is missing. If you are implementing these in a library replace:
xmlns:whatever="http://schemas.android.com/apk/res/org.example.mypackage"
with:
xmlns:whatever="http://schemas.android.com/apk/res-auto"
Otherwise the application that uses the library will have runtime errors.
Made a category like mxcl, but this is slightly faster.
My testing shows ~15% improvement (I could be wrong, feel free to compare the two yourself).
Basically I take the portion of the array thats in front of the object and the portion behind and combine them. Thus excluding the element.
- (NSArray *)prefix_arrayByRemovingObject:(id)object
{
if (!object) {
return self;
}
NSUInteger indexOfObject = [self indexOfObject:object];
NSArray *firstSubArray = [self subarrayWithRange:NSMakeRange(0, indexOfObject)];
NSArray *secondSubArray = [self subarrayWithRange:NSMakeRange(indexOfObject + 1, self.count - indexOfObject - 1)];
NSArray *newArray = [firstSubArray arrayByAddingObjectsFromArray:secondSubArray];
return newArray;
}
var arrayDiv = new Array();
for(var i=0; i <= 1; i++){
arrayDiv[i] = document.createElement('div');
arrayDiv[i].id = 'block' + i;
arrayDiv[i].className = 'block' + i;
}
document.body.appendChild(arrayDiv[0].appendChild(arrayDiv[1]));
Any class which extends Exception
class will be a user defined Checked exception class where as any class which extends RuntimeException
will be Unchecked exception class.
as mentioned in User defined exception are checked or unchecked exceptions
So, not throwing the checked exception(be it user-defined or built-in exception) gives compile time error.
Checked exception are the exceptions that are checked at compile time.
Unchecked exception are the exceptions that are not checked at compiled time
I made some benchmark tests and found, that the fastest way (by far) is this solution:
private static String removeLeadingZeros(String s) {
try {
Integer intVal = Integer.parseInt(s);
s = intVal.toString();
} catch (Exception ex) {
// whatever
}
return s;
}
Especially regular expressions are very slow in a long iteration. (I needed to find out the fastest way for a batchjob.)
A common mistake is
mainWB.Sheets.Add(After:=Sheets.Count)
which leads to Error 1004. Although it is not clear at all from the official documentation, it turns out that the 'After' parameter cannot be an integer, it must be a reference to a sheet in the same workbook.
Firstly add a div with id.
<div id="my_map_add" style="width:100%;height:300px;"></div>
<script type="text/javascript">
function my_map_add() {
var myMapCenter = new google.maps.LatLng(28.5383866, 77.34916609);
var myMapProp = {center:myMapCenter, zoom:12, scrollwheel:false, draggable:false, mapTypeId:google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("my_map_add"),myMapProp);
var marker = new google.maps.Marker({position:myMapCenter});
marker.setMap(map);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=your_key&callback=my_map_add"></script>
In case you are using Silex add the Symfony Asset as a dependency:
composer require symfony/asset
Then you may register Asset Service Provider:
$app->register(new Silex\Provider\AssetServiceProvider(), array(
'assets.version' => 'v1',
'assets.version_format' => '%s?version=%s',
'assets.named_packages' => array(
'css' => array(
'version' => 'css2',
'base_path' => __DIR__.'/../public_html/resources/css'
),
'images' => array(
'base_urls' => array(
'https://img.example.com'
)
),
),
));
Then in your Twig template file in head section:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
{% block head %}
<link rel="stylesheet" href="{{ asset('style.css') }}" />
{% endblock %}
</head>
<body>
</body>
</html>
--- create a ws server vs2012 upd 3
new project
choose .net framework 3.5
asp.net web service application
right click on the project root
choose add service reference
choose wsdl
--- how can I create a ws client from a wsdl file?
I´ve a ws server Axis2 under tomcat 7 and I want to test the compatibility
or, we can use something like this
dim i = dgv1.CurrentCellAddress.X
dim j = dgv1.CurrentCellAddress.Y
MsgBox(dgv1.Item(i,j).Value.ToString())
Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.
I realize this is stale for a while and an answer had been selected, but how about the alternative to allow the foreign key to be NULL and then choose ON DELETE SET NULL.
Basically, your table should be changed like so:
ALTER TABLE 'bericht'
DROP FOREIGN KEY 'your_foreign_key';
ALTER TABLE 'bericht'
ADD CONSTRAINT 'your_foreign_key' FOREIGN KEY ('column_foreign_key') REFERENCES 'other_table' ('column_parent_key') ON UPDATE CASCADE ON DELETE SET NULL;
Personally I would recommend using both "ON UPDATE CASCADE" as well as "ON DELETE SET NULL" to avoid unnecessary complications, however your set up may dictate a different approach.
Hope this helps.
Configuration for IntelliJ IDEA CE 2016.3.4 to enable JavaDocs on mouse hover. I am running IntelliJ IDEA on Mac OS but believe that Linux/Windows should have similar options.
Autopopup docs:
IntelliJ IDEA
> Preferences
> Editor
> General
> Code Completion
Documentation on mouse move:
IntelliJ IDEA
> Preferences
> Editor
> General
NOTE: Please hit Apply button to apply these settings
You can insert an image that looks like a button. Then attach a script to the image.
You can insert any image. The image can be edited in the spreadsheet
Image of a Button
Assign a function name to an image:
Friend, don't worry, if you have any application installed built in codeigniter and you wanna add some language pack just follow these steps:
1. Add language files in folder application/language/arabic (i add arabic lang in sma2 built in ci)
2. Go to the file named setting.php
in application/modules/settings/views/setting.php. Here you find the array
<?php /*
$lang = array (
'english' => 'English',
'arabic' => 'Arabic', // i add this here
'spanish' => 'Español'
Now save and run the application. It's worked fine.
CONVERT(varchar,GETDATE(),102)
What I learn about promises is to use it only as return values avoid referencing them if possible. async/await syntax is particularly practical for that. Today all latest browsers and node support it: https://caniuse.com/#feat=async-functions , is a simple behavior and the code is like reading synchronous code, forget about callbacks...
In cases I do need to reference a promises is when creation and resolution happen at independent/not-related places. So instead an artificial association and probably an event listener just to resolve the "distant" promise, I prefer to expose the promise as a Deferred, which the following code implements it in valid es5
/**
* Promise like object that allows to resolve it promise from outside code. Example:
*
```
class Api {
fooReady = new Deferred<Data>()
private knower() {
inOtherMoment(data=>{
this.fooReady.resolve(data)
})
}
}
```
*/
var Deferred = /** @class */ (function () {
function Deferred(callback) {
var instance = this;
this.resolve = null;
this.reject = null;
this.status = 'pending';
this.promise = new Promise(function (resolve, reject) {
instance.resolve = function () { this.status = 'resolved'; resolve.apply(this, arguments); };
instance.reject = function () { this.status = 'rejected'; reject.apply(this, arguments); };
});
if (typeof callback === 'function') {
callback.call(this, this.resolve, this.reject);
}
}
Deferred.prototype.then = function (resolve) {
return this.promise.then(resolve);
};
Deferred.prototype.catch = function (r) {
return this.promise.catch(r);
};
return Deferred;
}());
transpiled form a typescript project of mine:
For more complex cases I often use these guy small promise utilities without dependencies tested and typed. p-map has been useful several times. I think he covered most use cases:
https://github.com/sindresorhus?utf8=%E2%9C%93&tab=repositories&q=promise&type=source&language=
Tom's answer is quite detailed and exhaustive but you may also be interested in this simple study about Parquet vs Avro done at Allstate Insurance, summarized here:
"Overall, Parquet showed either similar or better results on every test [than Avro]. The query-performance differences on the larger datasets in Parquet’s favor are partly due to the compression results; when querying the wide dataset, Spark had to read 3.5x less data for Parquet than Avro. Avro did not perform well when processing the entire dataset, as suspected."
try this
Object.keys(data).length
If IE < 9, you can loop through the object yourself with a for loop
var len = 0;
var i;
for (i in data) {
if (data.hasOwnProperty(i)) {
len++;
}
}
add #include <iostream>
to the start of io.cpp
too.
Just remove the :
in your Quantity
. Make sure that your attribute is the same with the parameter you include in the code, like this:
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
If Me.DataGridView1.Rows(i).Cells("Quantity").Value < 5 Then
Me.DataGridView1.Rows(i).Cells("Quantity").Style.ForeColor = Color.Red
End If
Next
End Sub
You can execute your logic sequentially via synchronous executor nsynjs. It will pause on each promise, wait for resolution/rejection, and either assign resolve's result to data
property, or throw an exception (for handling that you will need try/catch block). Here is an example:
function synchronousCode() {_x000D_
function myFetch(url) {_x000D_
try {_x000D_
return window.fetch(url).data;_x000D_
}_x000D_
catch (e) {_x000D_
return {status: 'failed:'+e};_x000D_
};_x000D_
};_x000D_
var arr=[_x000D_
myFetch("https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"),_x000D_
myFetch("https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/NONEXISTANT.js"),_x000D_
myFetch("https://ajax.NONEXISTANT123.com/ajax/libs/jquery/2.0.0/NONEXISTANT.js")_x000D_
];_x000D_
_x000D_
console.log('array is ready:',arr[0].status,arr[1].status,arr[2].status);_x000D_
};_x000D_
_x000D_
nsynjs.run(synchronousCode,{},function(){_x000D_
console.log('done');_x000D_
});
_x000D_
<script src="https://rawgit.com/amaksr/nsynjs/master/nsynjs.js"></script>
_x000D_
I just encountered the same problem myself.
... = reader["myYear"] as int?;
works and is clean.
It works with any type without an issue. If the result is DBNull, it returns null as the conversion fails.
With regard to Tomcat, a lot depends on the particular version. There was a bug fix https://bz.apache.org/bugzilla/show_bug.cgi?id=50026 which means the servlet-mapping (other than for '/') for the default servlet behaves differently in Tomcat 6.0.29 (and earlier) compared with later versions.
this is to make display:inline-block work in all browsers:
Quirkly enough, in IE (6/7) , if you trigger hasLayout with "zoom:1" and then set the display to inline, it behaves as an inline block.
.inline-block {
display: inline-block;
zoom: 1;
*display: inline;
}
Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.
ASPX
<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
<ItemTemplate>
<div id="width:50%;height:30px;background:#0f0a0f;">
<asp:Label ID="lblSr" runat="server"
style="width:30%;float:left;text-align:right;text-indent:-2px;" />
<span
style="width:65%;float:right;text-align:left;text-indent:-2px;" >
<%# Eval("Item") %>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
Code Behind:
protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
{
Label l = e.Item.FindControl("lblSr") as Label;
if (l != null)
l.Text = e.Item.ItemIndex + 1+"";
}
Use "&
" instead of "&".
We don't have option to truncate dynamo tables. we have to drop the table and create again . DynamoDB Charges are based on ReadCapacityUnits & WriteCapacityUnits . If we delete all items using BatchWriteItem function, it will use WriteCapacityUnits.So better to delete specific records or delete the table and start again .
If the Proxy is which you trust, you can try: (Assume the Proxy IP is 151.101.2.10
)
<?php
$trustProxyIPs = ['151.101.2.10'];
$clientIP = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : NULL;
if (in_array($clientIP, $trustProxyIPs)) {
$headers = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR'];
foreach ($headers as $key => $header) {
if (isset($_SERVER[$header]) && filter_var($_SERVER[$header], FILTER_VALIDATE_IP)) {
$clientIP = $_SERVER[$header];
break;
}
}
}
echo $clientIP;
This will prevent forged forward header by direct requested clients, and get real IP via trusted Proxies.
for Kotilin implementation in the simplest form - only fires when screen changes from portrait <--> landscape if need device a flip detection (180 degree) you'll need to tab in to gravity sensor values
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rotation = windowManager.defaultDisplay.rotation
when (rotation) {
0 -> Log.d(TAG,"at zero degree")
1 -> Log.d(TAG,"at 270 degree")
2 -> Log.d(TAG,"at 180 degree")
3 -> Log.d(TAG,"at 90 degree")
}
}
You should stop the submit procedure by returning false on the onsubmit callback.
<script>
function checkRegistration(){
if(!form_valid){
alert('Given data is not correct');
return false;
}
return true;
}
</script>
<form onsubmit="return checkRegistration()"...
Here you have a fully working example. The form will submit only when you write google into input, otherwise it will return an error:
<script>
function checkRegistration(){
var form_valid = (document.getElementById('some_input').value == 'google');
if(!form_valid){
alert('Given data is incorrect');
return false;
}
return true;
}
</script>
<form onsubmit="return checkRegistration()" method="get" action="http://google.com">
Write google to go to google...<br/>
<input type="text" id="some_input" value=""/>
<input type="submit" value="google it"/>
</form>
Usually the problem is not closing brackets (}) or missing semicolon (;)
I know that you are looking for an auto-refresh; perhaps some coming in here may be happy with a quick fix for a manual button (like the checkbox proposed above). I actually just stumbled upon a similar solution to the checkbox: select the cells you want to refresh, and then press CTRL and the "+" key. Seems to work in Office 365 v16; hope it works for others in need.
Change
int wordLength = wordLengthFunction(string word);
to
int wordLength = wordLengthFunction(word);
You can do it with the code you have, you just need to ensure that html
and body
are set to 100% height.
Demo: http://jsfiddle.net/kevinPHPkevin/a7eGN/
html, body {
height:100%;
}
body {
background-color: white;
background-image: url('http://www.canvaz.com/portrait/charcoal-1.jpg');
background-size: auto 100%;
background-repeat: no-repeat;
background-position: left top;
}
@[User::path] ="MDS/Material/"+(DT_STR, 4, 1252) DATEPART("yy" , GETDATE())+ "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
You can use the react-moment package
-> https://www.npmjs.com/package/react-moment
Put in your file the next line:
import moment from "moment";
date_create: moment().format("DD-MM-YYYY hh:mm:ss")
Try this: Open given fiddle in CHROME
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
HTML
<input type="text" id="txt1" onkeyup="sum();" />
<input type="text" id="txt2" onkeyup="sum();" />
<input type="text" id="txt3" />
You can use find
and -exec
directly into sed
rather than first locating oldstr
with grep
. It's maybe a bit less efficient, but that might not be important. This way, the sed
replacement is executed over all files listed by find
, but if oldstr
isn't there it obviously won't operate on it.
find /path -type f -exec sed -i 's/oldstr/newstr/g' {} \;
I had the same issue and finally solved it. My mistake was that I tried to change /etc/php5/cli/php.ini, but then I found another php.ini here: /etc/php5/apache2/php.ini, changed display_errors = On, restarted the web-server and it worked!
May be it would be helpful for someone absent-minded like me.
Be sure to use quotes if there are spaces in the file path:
move "C:\Users\MyName\My Old Folder\*" "C:\Users\MyName\My New Folder"
That will move the contents of C:\Users\MyName\My Old Folder\
to C:\Users\MyName\My New Folder
select()
is a bit too low-level for convenience. I suggest you use the ncurses
library to put the terminal in cbreak mode and delay mode, then call getch()
, which will return ERR
if no character is ready:
WINDOW *w = initscr();
cbreak();
nodelay(w, TRUE);
At that point you can call getch
without blocking.
To check for null values you can use is_null() as is demonstrated below.
if (is_null($value)) {
$value = "MY TEXT"; //define to suit
}
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
If the image cannot be loaded (for example, because it is not present at the supplied URL), image URL will be changed into default,
For more about .error()
$('img').on('error', function (e) {_x000D_
$(this).attr('src', 'broken.png');_x000D_
});
_x000D_
Try your regex with a tool like http://jsregex.com/ (There is many) or better, a unit test.
For a naive validation:
function validateDate(testdate) {
var date_regex = /^\d{2}\/\d{2}\/\d{4}$/ ;
return date_regex.test(testdate);
}
In your case, to validate (MM/DD/YYYY), with a year between 1900 and 2099, I'll write it like that:
function validateDate(testdate) {
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
return date_regex.test(testdate);
}
UPDATE for .NET 5!
The below applies on/after NOV2020 when .NET 5 is officially out.
(see quick terminology section below, not just the How-to's)
dotnet publish --output "{any directory}" --runtime {runtime} --configuration {Debug|Release} -p:PublishSingleFile={true|false} -p:PublishTrimmed={true|false} --self-contained {true|false}
example:
dotnet publish --output "c:/temp/myapp" --runtime win-x64 --configuration Release -p:PublishSingleFile=true -p:PublishTrimmed=true --self-contained true
*In above 2 cases, the latest .net5 SDK will be automatically installed on your PC.
Click Start and choose Folder target, click next and choose Folder
Enter any folder location, and click Finish
Choose a Target Runtime and tick on Produce Single File and save.*
Click Publish
Open a terminal in the location you published your app, and run the .exe. Example:
Target Runtime
See the list of RID's
Deployment Mode
Enable ReadyToRun compilation
TLDR: it's .Net5's equivalent of Ahead of Time Compilation (AOT). Pre-compiled to native code, app would usually boot up faster. App more performant (or not!), depending on many factors. More info here
Trim unused assemblies
When set to true, dotnet will generate a very lean and small .exe and only include what it needs. Be careful here. Example: when using reflection in your app you probably don't want to set this flag to true.
Previous Post
UPDATE (31-OCT-2019)
For anyone that wants to do this via a GUI and:
Note
Notice the large file size for such a small application
You can add the "PublishTrimmed" property. The application will only include components that are used by the application. Caution: don't do this if you are using reflection
Publish again
Use the span tag with display:inline-block
css attached to it. You can then use CSS and manipulate it like a div in lots of ways but if you don't include a width
or height
it expands and retracts based on its content.
Hope that helps.
Use overflow-y
. This property is CSS 3.
x_train = x_train.reshape(-1,28, 28, 1) #Reshape for CNN - should work!!
x_test = x_test.reshape(-1,28, 28, 1)
history_cnn = cnn.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))
Output:
Train on 60000 samples, validate on 10000 samples Epoch 1/5 60000/60000 [==============================] - 157s 3ms/step - loss: 0.0981 - acc: 0.9692 - val_loss: 0.0468 - val_acc: 0.9861 Epoch 2/5 60000/60000 [==============================] - 157s 3ms/step - loss: 0.0352 - acc: 0.9892 - val_loss: 0.0408 - val_acc: 0.9879 Epoch 3/5 60000/60000 [==============================] - 159s 3ms/step - loss: 0.0242 - acc: 0.9924 - val_loss: 0.0291 - val_acc: 0.9913 Epoch 4/5 60000/60000 [==============================] - 165s 3ms/step - loss: 0.0181 - acc: 0.9945 - val_loss: 0.0361 - val_acc: 0.9888 Epoch 5/5 60000/60000 [==============================] - 168s 3ms/step - loss: 0.0142 - acc: 0.9958 - val_loss: 0.0354 - val_acc: 0.9906
Try GetElementsByTagName method of XMLDocument class to read specific data or LoadXml method to read all data to xml document.
There are a lot of good answers here with very accurate relational algebra examples. Here is a very simplified answer that might be helpful for amateur or novice coders with SQL coding dilemmas.
Basically, more often than not, JOIN
queries boil down to two cases:
For a SELECT
of a subset of A
data:
INNER JOIN
when the related B
data you are looking for MUST exist per database design;LEFT JOIN
when the related B
data you are looking for MIGHT or MIGHT NOT exist per database design.The gradle included with Android Studio is located in /Applications/Android Studio.app/plugins/gradle/lib
To go into the Android Studio.app directory I did cd "Android Studio.app"
or you could just do cd /Applications/Android\ Studio.app/plugins/gradle/lib
TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.
If you are calling a Python service, the code will look like below:
this.updateTalentSupplier=function(supplierObj){
var promise = $http({
method: 'POST',
url: bbConfig.BWS+'updateTalentSupplier/',
data:supplierObj,
withCredentials: false,
contentType:'application/json',
dataType:'json'
});
return promise; //Promise is returned
}
We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.
Now you can use "replaceAll":
console.log(' a b c d e f g '.replaceAll(' ',''));
will print:
abcdefg
But not working in every possible browser:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
Don'y forget that if you are mixing grouped (ie. SUM) fields and non-grouped fields, you need to GROUP BY one of the non-grouped fields.
Try this:
SELECT SUM(something) AS fieldname
FROM tablename
ORDER BY fieldname
OR this:
SELECT Field1, SUM(something) AS Field2
FROM tablename
GROUP BY Field1
ORDER BY Field2
And you can always do a derived query like this:
SELECT
f1, f2
FROM
(
SELECT SUM(x+y) as f1, foo as F2
FROM tablename
GROUP BY f2
) as table1
ORDER BY
f1
Many possibilities!
You shouldn't do that and that's not possible anyway, If you want you can set a greater value such as 10 years ahead.
By the way, I have never seen a cookie with such requirement :)
When the normType
is NORM_MINMAX
, cv::normalize
normalizes _src
in such a way that the min value of dst
is alpha
and max value of dst
is beta
. cv::normalize
does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).
CV_8UC1
says how many channels dst
has.
The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize
I started working on this problem a long time ago, trying to write my own binary to decimal converter function. I don't actually know how to convert decimal to binary though! I just revisited it today and figured it out and this is what I came up with. I'm not sure if this is what you need, but here it is:
def __degree(number):
power = 1
while number % (10**power) != number:
power += 1
return power
def __getDigits(number):
digits = []
degree = __degree(number)
for x in range(0, degree):
digits.append(int(((number % (10**(degree-x))) - (number % (10**(degree-x-1)))) / (10**(degree-x-1))))
return digits
def binaryToDecimal(number):
list = __getDigits(number)
decimalValue = 0
for x in range(0, len(list)):
if (list[x] is 1):
decimalValue += 2**(len(list) - x - 1)
return decimalValue
Again, I'm still learning Python just on my own, hopefully this helps. The first function determines how many digits there are, the second function actually figures out they are and returns them in a list, and the third function is the only one you actually need to call, and it calculates the decimal value. If your teacher actually wanted you to write your own converter, this works, I haven't tested it with every number, but it seems to work perfectly! I'm sure you'll all find the bugs for me! So anyway, I just called it like:
binaryNum = int(input("Enter a binary number: "))
print(binaryToDecimal(binaryNum))
This prints out the correct result. Cheers!
I did quickly fix it by going into "Design View" of the main Table of same Form and putting underline (_) between any field names that had spaces. I am now able to use the built in filters without the annoying popup about syntax problems.
To draw Horizontal
************************
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Center" Fill="DarkCyan" Height="4"/>
To draw vertical
*******************
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Center" Fill="DarkCyan" Height="4" Width="Auto" >
<Rectangle.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="90"/>
<TranslateTransform/>
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
Daniel is right: http://ideone.com/kgbo1C#view_edit_box
Change
test=substring(i,j,*s);
to
test=substring(i,j,s);
Also, you need to forward declare substring:
char *substring(int i,int j,char *ch);
int main // ...
Swift 4
import Foundation
let dateString = "2014-07-15" // change to your date format
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: dateString)
println(date)
Swift 3
import Foundation
var dateString = "2014-07-15" // change to your date format
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var date = dateFormatter.dateFromString(dateString)
println(date)
I can do it with this code.
Sorry for the late reply, but I think this is a good place to advertise my library ...
AFAIK, the standard library has only one module for playing audio: ossaudiodev. Sadly, this only works on Linux and FreeBSD.
UPDATE: There is also winsound, but obviously this is also platform-specific.
For something more platform-independent, you'll need to use an external library.
My recommendation is the sounddevice module (but beware, I'm the author).
The package includes the pre-compiled PortAudio library for Mac OS X and Windows, and can be easily installed with:
pip install sounddevice --user
It can play back sound from NumPy arrays, but it can also use plain Python buffers (if NumPy is not available).
To play back a NumPy array, that's all you need (assuming that the audio data has a sampling frequency of 44100 Hz):
import sounddevice as sd
sd.play(myarray, 44100)
For more details, have a look at the documentation.
It cannot read/write sound files, you'll need a separate library for that.
I hate to promote my own stuff (well, not really), but PowerPad can open very large files.
Otherwise, I'd recommend a hex editor.
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
You could do an SQLDump
of the database (and its data) then search that file.
pandoc is a nice Text-To-Text conversion tool that solves the problem of offline visualization of your Markdown. Just issue:
pandoc -f markdown -t html README.md > README.html
Answer on an old question, this new post is posted on April the 4th 2013
To complete the answer of @misza, here a advanced method to check if cookies are enabled without page reloading. The problem with @misza is that it not always work when the php ini setting session.use_cookies
is not true. Also the solution does not check if a session is already started.
I made this function and test it many times with in different situations and does the job very well.
function suGetClientCookiesEnabled() // Test if browser has cookies enabled
{
// Avoid overhead, if already tested, return it
if( defined( 'SU_CLIENT_COOKIES_ENABLED' ))
{ return SU_CLIENT_COOKIES_ENABLED; }
$bIni = ini_get( 'session.use_cookies' );
ini_set( 'session.use_cookies', 1 );
$a = session_id();
$bWasStarted = ( is_string( $a ) && strlen( $a ));
if( !$bWasStarted )
{
@session_start();
$a = session_id();
}
// Make a copy of current session data
$aSesDat = (isset( $_SESSION ))?$_SESSION:array();
// Now we destroy the session and we lost the data but not the session id
// when cookies are enabled. We restore the data later.
@session_destroy();
// Restart it
@session_start();
// Restore copy
$_SESSION = $aSesDat;
// If no cookies are enabled, the session differs from first session start
$b = session_id();
if( !$bWasStarted )
{ // If not was started, write data to the session container to avoid data loss
@session_write_close();
}
// When no cookies are enabled, $a and $b are not the same
$b = ($a === $b);
define( 'SU_CLIENT_COOKIES_ENABLED', $b );
if( !$bIni )
{ @ini_set( 'session.use_cookies', 0 ); }
//echo $b?'1':'0';
return $b;
}
Usage:
if( suGetClientCookiesEnabled())
{ echo 'Cookies are enabled!'; }
else { echo 'Cookies are NOT enabled!'; }
Important note: The function temporarily modify the ini setting of PHP when it not has the correct setting and restore it when it was not enabled. This is only to test if cookies are enabled. It can get go wrong when you start a session and the php ini setting session.use_cookies has an incorrect value. To be sure that the session is working correctly, check and/or set it before start a session, for example:
if( suGetClientCookiesEnabled())
{
echo 'Cookies are enabled!';
ini_set( 'session.use_cookies', 1 );
echo 'Starting session';
@start_session();
}
else { echo 'Cookies are NOT enabled!'; }
one things to remember push work only with array[] not object{}.
if you want to add Like object o inside inside n
_x000D_
_x000D_
a={ b:"c",
D:"e",
F: {g:"h",
I:"j",
k:{ l:"m"
}}
}
a.F.k.n = { o: "p" };
a.F.k.n = { o: "p" };
console.log(a);
_x000D_
_x000D_
_x000D_
A private setter is useful if you have a read only property and don't want to explicitly declare the backing variable.
So:
public int MyProperty
{
get; private set;
}
is the same as:
private int myProperty;
public int MyProperty
{
get { return myProperty; }
}
For non auto implemented properties it gives you a consistent way of setting the property from within your class so that if you need validation etc. you only have it one place.
To answer your final question the MSDN has this to say on private setters:
However, for small classes or structs that just encapsulate a set of values (data) and have little or no behaviors, it is recommended to make the objects immutable by declaring the set accessor as private.
You won't be able to do it in a single replacement; you'll have to perform a few steps. Here's how I'd do it:
Find (in regular expression mode):
(.+)
Replace with:
"\1"
This adds the quotes:
"AliceBlue"
"AntiqueWhite"
"Aqua"
"Aquamarine"
"Azure"
"Beige"
"Bisque"
"Black"
"BlanchedAlmond"
Find (in extended mode):
\r\n
Replace with (with a space after the comma, not shown):
,
This converts the lines into a comma-separated list:
"AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"
Add the var myArray =
assignment and braces manually:
var myArray = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"];
They are not doing the same job: $emit
dispatches an event upwards through the scope hierarchy, while $broadcast
dispatches an event downwards to all child scopes.
The error indicates that the two tables have the 1 or more column names that have the same column name.
Anyone with the same error who doesn't want to provide a suffix can rename the columns instead. Also make sure the index of both DataFrames match in type and value if you don't want to provide the on='mukey'
setting.
# rename example
df_a = df_a.rename(columns={'a_old': 'a_new', 'a2_old': 'a2_new'})
# set the index
df_a = df_a.set_index(['mukus'])
df_b = df_b.set_index(['mukus'])
df_a.join(df_b)
I'll throw another method on the pile...
scipy.interpolate
's many interpolating splines are capable of providing derivatives. So, using a linear spline (k=1
), the derivative of the spline (using the derivative()
method) should be equivalent to a forward difference. I'm not entirely sure, but I believe using a cubic spline derivative would be similar to a centered difference derivative since it uses values from before and after to construct the cubic spline.
from scipy.interpolate import InterpolatedUnivariateSpline
# Get a function that evaluates the linear spline at any x
f = InterpolatedUnivariateSpline(x, y, k=1)
# Get a function that evaluates the derivative of the linear spline at any x
dfdx = f.derivative()
# Evaluate the derivative dydx at each x location...
dydx = dfdx(x)