Follow the below steps,
Try preventing default on mousedown event:
<div onmousedown="event.preventDefault ? event.preventDefault() : event.returnValue = false">asd</div>
or
<div onmousedown="return false">asd</div>
querySelectorAll
function and split the values
string.Array#forEach
to iterate over every element from the values
array.Array#find
to find the option matching given value.selected
attribute to true
.Note: Array#from
transforms an array-like object into an array and then you are able to use Array.prototype
functions on it, like find or map.
var values = "Test,Prof,Off",_x000D_
options = Array.from(document.querySelectorAll('#strings option'));_x000D_
_x000D_
values.split(',').forEach(function(v) {_x000D_
options.find(c => c.value == v).selected = true;_x000D_
});
_x000D_
<select name='strings' id="strings" multiple style="width:100px;">_x000D_
<option value="Test">Test</option>_x000D_
<option value="Prof">Prof</option>_x000D_
<option value="Live">Live</option>_x000D_
<option value="Off">Off</option>_x000D_
<option value="On">On</option>_x000D_
</select>
_x000D_
open() will be called at the end of each of the fopen() family functions. open() is a system call and fopen() are provided by libraries as a wrapper functions for user easy of use
I would suggest:
DECLARE @sqlStatement nvarchar(MAX),
@tableName nvarchar(50) = 'TripEvent',
@columnName nvarchar(50) = 'CreatedDate';
SELECT @sqlStatement = 'ALTER TABLE ' + @tableName + ' DROP CONSTRAINT ' + dc.name + ';'
FROM sys.default_constraints AS dc
LEFT JOIN sys.columns AS sc
ON (dc.parent_column_id = sc.column_id)
WHERE dc.parent_object_id = OBJECT_ID(@tableName)
AND type_desc = 'DEFAULT_CONSTRAINT'
AND sc.name = @columnName
PRINT' ['+@tableName+']:'+@@SERVERNAME+'.'+DB_NAME()+'@'+CONVERT(VarChar, GETDATE(), 127)+'; '+@sqlStatement;
IF(LEN(@sqlStatement)>0)EXEC sp_executesql @sqlStatement
I went with the GIT_SSH environment variable. Here's my wrapper, similar to that from Joe Block from above, but handles any amount of arguments.
File ~/gitwrap.sh
#!/bin/bash
ssh -i ~/.ssh/gitkey_rsa "$@"
Then, in my .bashrc, add the following:
export GIT_SSH=~/gitwrap.sh
In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.
If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line
git config core.autocrlf true
If you want to make an intelligent decision how git should handle this, read the documentation
Here is a snippet
Formatting and Whitespace
Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.
core.autocrlf
If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.
Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:
$ git config --global core.autocrlf true
If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:
$ git config --global core.autocrlf input
This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.
If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:
$ git config --global core.autocrlf false
I wrote ublame
python tool that returns a naive history of a file commits that impacted a given search term, you'll find more information on the þroject page.
I needed a package from github that was written in typscript. I did a git pull of the most recent version from the master branch into the root of my main project. I then went into the directory and did an npm install so that the gulp commands would work that generates ES5 modules. Anyway, to make the long story short, my build process was trying to build files from this new folder so I had to move it out of my root. This was causing these same errors.
The following code snippet is an adaptation of Kendall Bennett's code for printing pdf files using the PdfiumViewer library. The main difference is that a Stream is used rather than a file.
public bool PrintPDF(
string printer,
string paperName,
int copies, Stream stream)
{
try
{
// Create the printer settings for our printer
var printerSettings = new PrinterSettings
{
PrinterName = printer,
Copies = (short)copies,
};
// Create our page settings for the paper size selected
var pageSettings = new PageSettings(printerSettings)
{
Margins = new Margins(0, 0, 0, 0),
};
foreach (PaperSize paperSize in printerSettings.PaperSizes)
{
if (paperSize.PaperName == paperName)
{
pageSettings.PaperSize = paperSize;
break;
}
}
// Now print the PDF document
using (var document = PdfiumViewer.PdfDocument.Load(stream))
{
using (var printDocument = document.CreatePrintDocument())
{
printDocument.PrinterSettings = printerSettings;
printDocument.DefaultPageSettings = pageSettings;
printDocument.PrintController = new StandardPrintController();
printDocument.Print();
}
}
return true;
}
catch (System.Exception e)
{
return false;
}
}
In my case I am generating the PDF file using a library called PdfSharp and then saving the document to a Stream like so:
PdfDocument pdf = PdfGenerator.GeneratePdf(printRequest.html, PageSize.A4);
pdf.AddPage();
MemoryStream stream = new MemoryStream();
pdf.Save(stream);
MemoryStream stream2 = new MemoryStream(stream.ToArray());
One thing that I want to point out that might be helpful to other developers is that I had to install the 32 bit version of the pdfuim native dll in order for the printing to work even though I am running Windows 10 64 bit. I installed the following two NuGet packages using the NuGet package manager in Visual Studio:
Try mpstat
from the sysstat
package
> sudo apt-get install sysstat
Linux 3.0.0-13-generic (ws025) 02/10/2012 _x86_64_ (2 CPU)
03:33:26 PM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle
03:33:26 PM all 2.39 0.04 0.19 0.34 0.00 0.01 0.00 0.00 97.03
Then some cut
or grep
to parse the info you need:
mpstat | grep -A 5 "%idle" | tail -n 1 | awk -F " " '{print 100 - $ 12}'a
Actually I used my script in html directly. But in javascript when you add oninput event listener for this event it gives the data automatically.You just need to assign the value as per your requirement.
[slider] {_x000D_
width: 300px;_x000D_
position: relative;_x000D_
height: 5px;_x000D_
margin: 45px 0 10px 0;_x000D_
}_x000D_
_x000D_
[slider] > div {_x000D_
position: absolute;_x000D_
left: 13px;_x000D_
right: 15px;_x000D_
height: 5px;_x000D_
}_x000D_
[slider] > div > [inverse-left] {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
height: 5px;_x000D_
border-radius: 10px;_x000D_
background-color: #CCC;_x000D_
margin: 0 7px;_x000D_
}_x000D_
_x000D_
[slider] > div > [inverse-right] {_x000D_
position: absolute;_x000D_
right: 0;_x000D_
height: 5px;_x000D_
border-radius: 10px;_x000D_
background-color: #CCC;_x000D_
margin: 0 7px;_x000D_
}_x000D_
_x000D_
_x000D_
[slider] > div > [range] {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
height: 5px;_x000D_
border-radius: 14px;_x000D_
background-color: #d02128;_x000D_
}_x000D_
_x000D_
[slider] > div > [thumb] {_x000D_
position: absolute;_x000D_
top: -7px;_x000D_
z-index: 2;_x000D_
height: 20px;_x000D_
width: 20px;_x000D_
text-align: left;_x000D_
margin-left: -11px;_x000D_
cursor: pointer;_x000D_
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.4);_x000D_
background-color: #FFF;_x000D_
border-radius: 50%;_x000D_
outline: none;_x000D_
}_x000D_
_x000D_
[slider] > input[type=range] {_x000D_
position: absolute;_x000D_
pointer-events: none;_x000D_
-webkit-appearance: none;_x000D_
z-index: 3;_x000D_
height: 14px;_x000D_
top: -2px;_x000D_
width: 100%;_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]:focus::-webkit-slider-runnable-track {_x000D_
background: transparent;_x000D_
border: transparent;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]:focus {_x000D_
outline: none;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]::-webkit-slider-thumb {_x000D_
pointer-events: all;_x000D_
width: 28px;_x000D_
height: 28px;_x000D_
border-radius: 0px;_x000D_
border: 0 none;_x000D_
background: red;_x000D_
-webkit-appearance: none;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]::-ms-fill-lower {_x000D_
background: transparent;_x000D_
border: 0 none;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]::-ms-fill-upper {_x000D_
background: transparent;_x000D_
border: 0 none;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]::-ms-tooltip {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
[slider] > div > [sign] {_x000D_
opacity: 0;_x000D_
position: absolute;_x000D_
margin-left: -11px;_x000D_
top: -39px;_x000D_
z-index:3;_x000D_
background-color: #d02128;_x000D_
color: #fff;_x000D_
width: 28px;_x000D_
height: 28px;_x000D_
border-radius: 28px;_x000D_
-webkit-border-radius: 28px;_x000D_
align-items: center;_x000D_
-webkit-justify-content: center;_x000D_
justify-content: center;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
[slider] > div > [sign]:after {_x000D_
position: absolute;_x000D_
content: '';_x000D_
left: 0;_x000D_
border-radius: 16px;_x000D_
top: 19px;_x000D_
border-left: 14px solid transparent;_x000D_
border-right: 14px solid transparent;_x000D_
border-top-width: 16px;_x000D_
border-top-style: solid;_x000D_
border-top-color: #d02128;_x000D_
}_x000D_
_x000D_
[slider] > div > [sign] > span {_x000D_
font-size: 12px;_x000D_
font-weight: 700;_x000D_
line-height: 28px;_x000D_
}_x000D_
_x000D_
[slider]:hover > div > [sign] {_x000D_
opacity: 1;_x000D_
}
_x000D_
<div slider id="slider-distance">_x000D_
<div>_x000D_
<div inverse-left style="width:70%;"></div>_x000D_
<div inverse-right style="width:70%;"></div>_x000D_
<div range style="left:0%;right:0%;"></div>_x000D_
<span thumb style="left:0%;"></span>_x000D_
<span thumb style="left:100%;"></span>_x000D_
<div sign style="left:0%;">_x000D_
<span id="value">0</span>_x000D_
</div>_x000D_
<div sign style="left:100%;">_x000D_
<span id="value">100</span>_x000D_
</div>_x000D_
</div>_x000D_
<input type="range" value="0" max="100" min="0" step="1" oninput="_x000D_
this.value=Math.min(this.value,this.parentNode.childNodes[5].value-1);_x000D_
let value = (this.value/parseInt(this.max))*100_x000D_
var children = this.parentNode.childNodes[1].childNodes;_x000D_
children[1].style.width=value+'%';_x000D_
children[5].style.left=value+'%';_x000D_
children[7].style.left=value+'%';children[11].style.left=value+'%';_x000D_
children[11].childNodes[1].innerHTML=this.value;" />_x000D_
_x000D_
<input type="range" value="100" max="100" min="0" step="1" oninput="_x000D_
this.value=Math.max(this.value,this.parentNode.childNodes[3].value-(-1));_x000D_
let value = (this.value/parseInt(this.max))*100_x000D_
var children = this.parentNode.childNodes[1].childNodes;_x000D_
children[3].style.width=(100-value)+'%';_x000D_
children[5].style.right=(100-value)+'%';_x000D_
children[9].style.left=value+'%';children[13].style.left=value+'%';_x000D_
children[13].childNodes[1].innerHTML=this.value;" />_x000D_
</div>
_x000D_
iOS13+ //top Most view Controller
extension UIViewController {
func topMostViewController() -> UIViewController {
if self.presentedViewController == nil {
return self
}
if let navigation = self.presentedViewController as? UINavigationController {
return navigation.visibleViewController!.topMostViewController()
}
if let tab = self.presentedViewController as? UITabBarController {
if let selectedTab = tab.selectedViewController {
return selectedTab.topMostViewController()
}
return tab.topMostViewController()
}
return self.presentedViewController!.topMostViewController()
}
}
extension UIApplication {
func topMostViewController() -> UIViewController? {
return UIWindow.key!.rootViewController?.topMostViewController()
}
}
extension UIWindow {
static var key: UIWindow? {
if #available(iOS 13, *) {
return UIApplication.shared.windows.first { $0.isKeyWindow }
} else {
return UIApplication.shared.keyWindow
}
}
}
//use let vc = UIApplication.shared.topMostViewController()
// End top Most view Controller
This worked for me:
set(SOURCE main.cpp)
add_executable(${PROJECT_NAME} ${SOURCE})
# target_include_directories must be added AFTER add_executable
target_include_directories(${PROJECT_NAME} PUBLIC ${INTERNAL_INCLUDES})
In addition to the answer from @StephanBijzitter I would use the following PATH
variables instead:
%appdata%\npm
%ProgramFiles%\nodejs
So your new PATH
would look like:
[existing stuff];%appdata%\npm;%ProgramFiles%\nodejs
This has the advantage of neiter being user dependent nor 32/64bit dependent.
It's the other way around: B.class.isInstance(view)
In general,
variable=$(command)
or
variable=`command`
The latter one is the old syntax, prefer $(command)
.
Note: variable = ....
means execute the command variable
with the first argument =
, the second ....
For reading/writing excel files, you can use :
readxl
package for reading and writexl
package for writingopenxlsx
package for reading and writingWith xlsx
and XLConnect
(which use rjava) you will face memory errors if you have large files
It sounds like the populate method is what your looking for. First make small change to your post schema:
var postSchema = new Schema({
name: String,
postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Then make your model:
var Post = mongoose.model('Post', postSchema);
Then, when you make your query, you can populate references like this:
Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
// do stuff with post
});
I got rid of my issue by changing File > Workspace and then, after the restart, reset the Workspace again.
Yes, 1 byte does encode a character (inc spaces etc) from the ASCII set. However in data units assigned to character encoding it can and often requires in practice up to 4 bytes. This is because English is not the only character set. And even in English documents other languages and characters are often represented. The numbers of these are very many and there are very many other encoding sets, which you may have heard of e.g. BIG-5, UTF-8, UTF-32. Most computers now allow for these uses and ensure the least amount of garbled text (which usually means a missing encoding set.) 4 bytes is enough to cover these possible encodings. I byte per character does not allow for this and in use it is larger often 4 bytes per possible character for all encodings, not just ASCII. The final character may only need a byte to function or be represented on screen, but requires 4 bytes to be located in the rather vast global encoding "works".
Answers provided here as which camera api to use are wrong. Or better to say they are insufficient.
Some phones (for example Samsung Galaxy S6) could be above api level 21 but still may not support Camera2 api.
CameraCharacteristics mCameraCharacteristics = mCameraManager.getCameraCharacteristics(mCameraId);
Integer level = mCameraCharacteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
if (level == null || level == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
return false;
}
CameraManager class in Camera2Api has a method to read camera characteristics. You should check if hardware wise device is supporting Camera2 Api or not.
But there are more issues to handle if you really want to make it work for a serious application: Like, auto-flash option may not work for some devices or battery level of the phone might create a RuntimeException on Camera or phone could return an invalid camera id and etc.
So best approach is to have a fallback mechanism as for some reason Camera2 fails to start you can try Camera1 and if this fails as well you can make a call to Android to open default Camera for you.
Before MVC 5 you could map URLs to specific actions and controllers by calling routes.MapRoute(...)
in the RouteConfig.cs file. This is where the url for the homepage is stored (Home/Index
). However if you modify the default route as shown below,
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
keep in mind that this will affect the URLs of other actions and controllers. For example, if you had a controller class named ExampleController
and an action method inside of it called DoSomething
, then the expected default url ExampleController/DoSomething
will no longer work because the default route was changed.
A workaround for this is to not mess with the default route and create new routes in the RouteConfig.cs file for other actions and controllers like so,
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Example",
url: "hey/now",
defaults: new { controller = "Example", action = "DoSomething", id = UrlParameter.Optional }
);
Now the DoSomething
action of the ExampleController
class will be mapped to the url hey/now
. But this can get tedious to do for every time you want to define routes for different actions. So in MVC 5 you can now add attributes to match urls to actions like so,
public class HomeController : Controller
{
// url is now 'index/' instead of 'home/index'
[Route("index")]
public ActionResult Index()
{
return View();
}
// url is now 'create/new' instead of 'home/create'
[Route("create/new")]
public ActionResult Create()
{
return View();
}
}
I had originally decided to use a static field in my API class to reference an instance of MyDataContext object (Where MyDataContext is an EF5 Context object), but that is what seemed to create the problem. I added code something like the following to every one of my API methods and that fixed the problem.
using(MyDBContext db = new MyDBContext())
{
//Do some linq queries
}
As other people have stated, the EF Data Context objects are NOT thread safe. So placing them in the static object will eventually cause the "data reader" error under the right conditions.
My original assumption was that creating only one instance of the object would be more efficient, and afford better memory management. From what I have gathered researching this issue, that is not the case. In fact, it seems to be more efficient to treat each call to your API as an isolated, thread safe event. Ensuring that all resources are properly released, as the object goes out of scope.
This makes sense especially if you take your API to the next natural progression which would be to expose it as a WebService or REST API.
Disclosure
In Configure method declare your role manager (Startup)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, RoleManager<IdentityRole> roleManager)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Task.Run(()=>this.CreateRoles(roleManager)).Wait();
}
private async Task CreateRoles(RoleManager<IdentityRole> roleManager)
{
foreach (string rol in this.Configuration.GetSection("Roles").Get<List<string>>())
{
if (!await roleManager.RoleExistsAsync(rol))
{
await roleManager.CreateAsync(new IdentityRole(rol));
}
}
}
OPTIONAL - In appsettings.JSON (it depends on you where you wanna get roles from)
{
"Roles": [
"SuperAdmin",
"Admin",
"Employee",
"Customer"
]
}
Another solution, you can solve your problem using replaceAll
with some regex ^.{1}
(regex demo) for example :
String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica
In some cases, when you check your default encoding (print sys.getdefaultencoding()
), it returns that you are using ASCII. If you change to UTF-8, it doesn't work, depending on the content of your variable.
I found another way:
import sys
reload(sys)
sys.setdefaultencoding('Cp1252')
Also you can just login with windows authentication and run the following query to enable it:
ALTER LOGIN sa ENABLE ;
GO
ALTER LOGIN sa WITH PASSWORD = '<enterStrongPasswordHere>' ;
GO
You need to consider the way the datediff command rounds.
SELECT CASE WHEN dateadd(year, datediff (year, DOB, getdate()), DOB) > getdate()
THEN datediff(year, DOB, getdate()) - 1
ELSE datediff(year, DOB, getdate())
END as Age
FROM <table>
Which I adapted from here.
Note that it will consider 28th February as the birthday of a leapling for non-leap years e.g. a person born on 29 Feb 2020 will be considered 1 year old on 28 Feb 2021 instead of 01 Mar 2021.
To update a table in your .dbml-diagram with, for example, added columns, do this:
I've solved this problem in this way.
String dateUTC = rs.getString("date"); //UTC
DateTime date;
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").withZoneUTC();
date = dateTimeFormatter.parseDateTime(dateUTC);
In this way you ignore the server TimeZone forcing your chosen TimeZone.
I believe your question is to change only width of view dynamically, whereas above methods will change layout properties completely to new one, so I suggest to getLayoutParams() from view first, then set width on layoutParams, and finally set layoutParams to the view, so following below steps to do the same.
View view = findViewById(R.id.nutrition_bar_filled);
LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = newWidth;
view.setLayoutParams(layoutParams);
This one is for all the Maven users out there, using their dependencies for the classpath and not copying them into /WEB-INF/lib:
just add this (which copies the dependency libraries) before </plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>process-sources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>WebContent/WEB-INF/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
If JSON conventions are enough for the unescaped strings you want to get escaped and you already use Newtonsoft.Json
in your project (it has a pretty large overhead) you may use this package like the following:
using System;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
Console.WriteLine(ToLiteral( @"abc\n123") );
}
private static string ToLiteral(string input){
return JsonConvert.DeserializeObject<string>("\"" + input + "\"");
}
}
implements
means a behaviour will be defined for abstract
methods (except for abstract classes obviously), you define the implementation.
extends
means that a behaviour is inherited.
With interfaces it is possible to say that one interface should have that the same behaviour as another, there is not even an actual implementation. That's why it makes more sense for an interface to extends
another interface instead of implementing it.
On a side note, remember that even if an abstract
class can define abstract
methods (the sane way an interface does), it is still a class and still has to be inherited (extended) and not implemented.
This might be better understood if you modified the wording up a bit:
var buttons = {
foo: 'bar',
fiz: 'buz'
};
for ( var property in buttons ) {
console.log( property ); // Outputs: foo, fiz or fiz, foo
}
Note here that you're iterating over the properties of the object, using property
as a reference to each during each subsequent cycle.
MSDN says of for ( variable in [object | array ] )
the following:
Before each iteration of a loop, variable is assigned the next property name of object or the next element index of array. You can then use it in any of the statements inside the loop to reference the property of object or the element of array.
Note also that the property order of an object is not constant, and can change, unlike the index order of an array. That might come in handy.
OK, so thanks to all of the contributors above. I am using .NET 4.6 and we also had the same issue. I spent time debugging System.Net.Http
, specifically the HttpClientHandler
, and found the following:
if (ExecutionContext.IsFlowSuppressed())
{
IWebProxy webProxy = (IWebProxy) null;
if (this.useProxy)
webProxy = this.proxy ?? WebRequest.DefaultWebProxy;
if (this.UseDefaultCredentials || this.Credentials != null || webProxy != null && webProxy.Credentials != null)
this.SafeCaptureIdenity(state);
}
So after assessing that the ExecutionContext.IsFlowSuppressed()
might have been the culprit, I wrapped our Impersonation code as follows:
using (((WindowsIdentity)ExecutionContext.Current.Identity).Impersonate())
using (System.Threading.ExecutionContext.SuppressFlow())
{
// HttpClient code goes here!
}
The code inside of SafeCaptureIdenity
(not my spelling mistake), grabs WindowsIdentity.Current()
which is our impersonated identity. This is being picked up because we are now suppressing flow. Because of the using/dispose this is reset after invocation.
It now seems to work for us, phew!
For me, I tried to check out a SVN-project with TortoiseGit. It worked fine if I used TortoiseSVN though. (May seem obvious, but newcomers may stumble on this one)
I had this issue with cap = cv2.VideoCapture(0). I changed this to cap = cv2.VideoCapture(1) and then it worked. Since it wasn't linked to the right webcam it was returning nothing. Maybe this will help good luck.
Adding the jquery*.js file reference twice can also cause the issue. It could be part of your bundle and you might have added to the page too. Hence you need to remove the additional reference like
Use the View for your efforts in altering the position of the column: CREATE VIEW CORRECTED_POSITION AS SELECT co1_1, col_3, col_2 FROM UNORDERDED_POSITION should help.
This requests are made so some reports get produced where it is using SELECT * FROM [table_name]. Or, some business has a hierarchy approach of placing the information in order for better readability from the back end.
Thanks Dilip
You should convert first DataSource
in BindingSource
, look example
BindingSource bs = (BindingSource)dgrid.DataSource; // Se convierte el DataSource
DataTable tCxC = (DataTable) bs.DataSource;
With the data of tCxC
you can do anything.
Additionally there is PDFTextStream which is a commercial Java library that can also be used from Python.
You should include the repository where you want to deploy in the distribution management section of the pom.xml
.
Example:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
...
<distributionManagement>
<repository>
<uniqueVersion>false</uniqueVersion>
<id>corp1</id>
<name>Corporate Repository</name>
<url>scp://repo/maven2</url>
<layout>default</layout>
</repository>
...
</distributionManagement>
...
</project>
def nans(df): return df[df.isnull().any(axis=1)]
then when ever you need it you can type:
nans(your_dataframe)
With a Microsoft compiler[1], static variables that are not int
-like can also be defined in a header file, but outside of the class declaration, using the Microsoft specific __declspec(selectany)
.
class A
{
static B b;
}
__declspec(selectany) A::b;
Note that I'm not saying this is good, I just say it can be done.
[1] These days, more compilers than MSC support __declspec(selectany)
- at least gcc and clang. Maybe even more.
Something like this should work:
INSERT INTO #IMEIS (imei) VALUES ('val1'), ('val2'), ...
UPDATE:
Apparently this syntax is only available starting on SQL Server 2008.
I think you can use this code also: and you can manage your class css better
<style>
.navigationClass{
display: inline-block;
padding: 0px 0px 0px 6px;
background-color: whitesmoke;
border-radius: 2px;
}
</style>
<div id="header" class="row">
<div id="logo" class="col_12">And the winner is<span>n't...</span></div>
<div id="navigation" class="row">
<ul id="pirra">
<li><a href="#">Why?</a></li>
<li><a href="#">Synopsis</a></li>
<li><a href="#">Stills/Photos</a></li>
<li><a href="#">Videos/clips</a></li>
<li><a href="#">Quotes</a></li>
<li><a href="#">Quiz</a></li>
</ul>
</div>
<script>
$(document).ready(function() {
$('#navigation ul li').addClass('navigationClass'); //add class navigationClass to the #navigation .
});
</script>
PID=`ps -ef | grep syncapp 'awk {print $2}'`
if [[ -z "$PID" ]] then
**Kill -9 $PID**
fi
I had an issue related to this and was reading
"Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\opencv\build\java\x86\opencv_java2413.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform "
and it took me an entire night to figure out.
I solved my problem by copying the dll in C:\opencv\build\java\x64
to my system32 folder. I hope this will be of help to someone.
I wrote a simpler loop that works too (note that all my values are unique):
HashMap<Character, String> myHashMap = new HashMap<Character, String>();
HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
for (char i : myHashMap.keySet()) {
reversedHashMap.put(myHashMap.get(i), i);
}
Depending on the purpose of setting the display property, you might want to take a look at
$("#yourElementID").show()
and
$("#yourElementID").hide()
Telnet to the host at port 80.
Type:
get / http1.1
::enter::
::enter::
It is kind of an HTTP request, but it's not valid so the 500 error it gives you will probably give you the information you want. The blank lines at the end are important otherwise it will just seem to hang.
Try this solution:
public class Anagramm {
public static boolean isAnagramLetters(String word, String anagramm) {
if (anagramm.isEmpty()) {
return false;
}
Map<Character, Integer> mapExistString = CharCountMap(word);
Map<Character, Integer> mapCheckString = CharCountMap(anagramm);
return enoughLetters(mapExistString, mapCheckString);
}
private static Map<Character, Integer> CharCountMap(String chars) {
HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();
for (char c : chars.toCharArray()) {
if (charCountMap.containsKey(c)) {
charCountMap.put(c, charCountMap.get(c) + 1);
} else {
charCountMap.put(c, 1);
}
}
return charCountMap;
}
static boolean enoughLetters(Map<Character, Integer> mapExistString, Map<Character,Integer> mapCheckString) {
for( Entry<Character, Integer> e : mapCheckString.entrySet() ) {
Character letter = e.getKey();
Integer available = mapExistString.get(letter);
if (available == null || e.getValue() > available) return false;
}
return true;
}
}
Complementing the @NoahD's answer
To have a greater precision you can cast to decimal:
(decimal)100/863
//0.1158748551564310544611819235
Or:
Decimal.Divide(100, 863)
//0.1158748551564310544611819235
Double are represented allocating 64 bits while decimal uses 128
(double)100/863
//0.11587485515643106
For more details about the floating point representation in binary and its precision take a look at this article from Jon Skeet where he talks about floats
and doubles
and this one where he talks about decimals
.
You could just check if the Year number is divisible by both 4 and 400. You dont really need to check if it is indivisible by 100. The reason 400 comes into question is because according to the Gregorian Calendar, our "day length" is slightly off, and thus to compensate that, we have 303 regular years (365 days each) and 97 leap years (366 days each). The difference of those 3 extra years that are not leap years is to stay in cycle with the Gregorian calendar, which repeats every 400 years. Look up Christian Zeller's congruence equation. It will help understanding the real reason. Hope this helps :)
Fiddler is the winner every time when comparing to Charles.
The "customize rules" feature of fiddler is unparalleled in any http debugger. The ability to write code to manipulate http requests and responses on-the-fly is invaluable to me and the work I do in web development.
There are so many features to fiddler that charles just does not have, and likely won't ever have. Fiddler is light-years ahead.
python3x or higher
body = ''
for lines in open('website/index.html','rb'):
decodedLine = lines.decode('utf-8')
body = body+decodedLine.strip()
return body
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
Session.contains(Object obj)
checks the reference and will not detect a different instance that represents the same row and is already attached to it.
Here my generic solution for Entities with an identifier property.
public static void update(final Session session, final Object entity)
{
// if the given instance is in session, nothing to do
if (session.contains(entity))
return;
// check if there is already a different attached instance representing the same row
final ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(entity.getClass());
final Serializable identifier = classMetadata.getIdentifier(entity, (SessionImplementor) session);
final Object sessionEntity = session.load(entity.getClass(), identifier);
// override changes, last call to update wins
if (sessionEntity != null)
session.evict(sessionEntity);
session.update(entity);
}
This is one of the few aspects of .Net EntityFramework I like, the different attach options regarding changed entities and their properties.
You need to write this inside the corresponding CSS
table-layout:fixed;
if ($('input:checkbox').filter(':checked').length < 1){
alert("Check at least one!");
return false;
}
It's used for proxying requests to other servers.
An example from http://wiki.nginx.org/LoadBalanceExample is:
http {
upstream myproject {
server 127.0.0.1:8000 weight=3;
server 127.0.0.1:8001;
server 127.0.0.1:8002;
server 127.0.0.1:8003;
}
server {
listen 80;
server_name www.domain.com;
location / {
proxy_pass http://myproject;
}
}
}
This means all requests for / go to the any of the servers listed under upstream XXX, with a preference for port 8000.
If you want Selected.Value being worked you have to do following things:
1. Set DisplayMember
2. Set ValueMember
3. Set DataSource (not use Items.Add, Items.AddRange, DataBinding etc.)
The key point is Set DataSource!
script function to add cronjobs. check duplicate entries,useable expressions * > "
cronjob_creator () {
# usage: cronjob_creator '<interval>' '<command>'
if [[ -z $1 ]] ;then
printf " no interval specified\n"
elif [[ -z $2 ]] ;then
printf " no command specified\n"
else
CRONIN="/tmp/cti_tmp"
crontab -l | grep -vw "$1 $2" > "$CRONIN"
echo "$1 $2" >> $CRONIN
crontab "$CRONIN"
rm $CRONIN
fi
}
tested :
$ ./cronjob_creator.sh '*/10 * * * *' 'echo "this is a test" > export_file'
$ crontab -l
$ */10 * * * * echo "this is a test" > export_file
source : my brain ;)
function foo(data)
{
// do stuff with JSON
}
var script = document.createElement('script');
script.src = '//example.com/path/to/jsonp?callback=foo'
document.getElementsByTagName('head')[0].appendChild(script);
// or document.head.appendChild(script) in modern browsers
You shouldn't use float unless you have to. In 99% of cases, double is a better choice.
int x = 1111111111;
int y = 10000;
float f = (float) x / y;
double d = (double) x / y;
System.out.println("f= "+f);
System.out.println("d= "+d);
prints
f= 111111.12
d= 111111.1111
Following @Matt's comment.
float has very little precision (6-7 digits) and shows significant rounding error fairly easily. double has another 9 digits of accuracy. The cost of using double instead of float is notional in 99% of cases however the cost of a subtle bug due to rounding error is much higher. For this reason, many developers recommend not using floating point at all and strongly recommend BigDecimal.
However I find that double can be used in most cases provided sensible rounding is used.
In this case, int x has 32-bit precision whereas float has a 24-bit precision, even dividing by 1 could have a rounding error. double on the other hand has 53-bit of precision which is more than enough to get a reasonably accurate result.
Visual Studio 2013: Yes to both adding to the watch windows during debugging and dragging variables or typing them in without "user::". But before any of that would work I also needed to go to Tools > Options, then Debugging > General and had to scroll right down to the bottom of the right hand pane to be able to tick "Use Managed Compatibility Mode". Then I had to stop and restart debugging. Finally the above advice worked. Many thanks to the above and to this article: Visual Studio 2015 Debugging: Can't expand local variables?
Just press ?K it will toggle keyboard.
The problem you face is that you try to assign the return of imshow
(which is an matplotlib.image.AxesImage
to an existing axes object.
The correct way of plotting image data to the different axes in axarr
would be
f, axarr = plt.subplots(2,2)
axarr[0,0].imshow(image_datas[0])
axarr[0,1].imshow(image_datas[1])
axarr[1,0].imshow(image_datas[2])
axarr[1,1].imshow(image_datas[3])
The concept is the same for all subplots, and in most cases the axes instance provide the same methods than the pyplot (plt) interface.
E.g. if ax
is one of your subplot axes, for plotting a normal line plot you'd use ax.plot(..)
instead of plt.plot()
. This can actually be found exactly in the source from the page you link to.
i found mine here:
~/android-sdks/platforms/android-23/data/res/drawable...
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
This snippet provides the functionality you require. What you need to do is add an event to that div that which activates fnSelect in it. A quick hack that you totally shouldn't do and possibly might not work, would look like this:
document.getElementById("selectable").onclick(function(){
fnSelect("selectable");
});
Obviously assuming that the linked to snippet had been included.
In my case I had to uninstall and reinstall the wireless adapter driver to be able to execute the command
df=pd.read_csv("filename.csv" , parse_dates=["<column name>"])
type(df.<column name>)
example: if you want to convert day which is initially a string to a Timestamp in Pandas
df=pd.read_csv("weather_data2.csv" , parse_dates=["day"])
type(df.day)
The output will be pandas.tslib.Timestamp
/**
* Date to timestamp
* @param string template
* @param string date
* @return string
* @example datetotime("d-m-Y", "26-02-2012") return 1330207200000
*/
function datetotime(template, date){
date = date.split( template[1] );
template = template.split( template[1] );
date = date[ template.indexOf('m') ]
+ "/" + date[ template.indexOf('d') ]
+ "/" + date[ template.indexOf('Y') ];
return (new Date(date).getTime());
}
You have to select the sheet before you can select the range.
I've simplified the example to isolate the problem. Try this:
Option Explicit
Sub RangeError()
Dim sourceBook As Workbook
Dim sourceSheet As Worksheet
Dim sourceSheetSum As Worksheet
Set sourceBook = ActiveWorkbook
Set sourceSheet = sourceBook.Sheets("Sheet1")
Set sourceSheetSum = sourceBook.Sheets("Sheet2")
sourceSheetSum.Select
sourceSheetSum.Range("C3").Select 'THIS IS THE PROBLEM LINE
End Sub
Replace Sheet1 and Sheet2 with your sheet names.
IMPORTANT NOTE: Using Variants is dangerous and can lead to difficult-to-kill bugs. Use them only if you have a very specific reason for doing so.
In my opinion, to answer this question, you need to think in terms of project life cycle and version control. In other words, does the parent pom have its own life cycle i.e. can it be released separately of the other modules or not?
If the answer is yes (and this is the case of most projects that have been mentioned in the question or in comments), then the parent pom needs his own module from a VCS and from a Maven point of view and you'll end up with something like this at the VCS level:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
`-- projectA
|-- branches
|-- tags
`-- trunk
|-- module1
| `-- pom.xml
|-- moduleN
| `-- pom.xml
`-- pom.xml
This makes the checkout a bit painful and a common way to deal with that is to use svn:externals
. For example, add a trunks
directory:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
|-- projectA
| |-- branches
| |-- tags
| `-- trunk
| |-- module1
| | `-- pom.xml
| |-- moduleN
| | `-- pom.xml
| `-- pom.xml
`-- trunks
With the following externals definition:
parent-pom http://host/svn/parent-pom/trunk
projectA http://host/svn/projectA/trunk
A checkout of trunks
would then result in the following local structure (pattern #2):
root/
parent-pom/
pom.xml
projectA/
Optionally, you can even add a pom.xml
in the trunks
directory:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
|-- projectA
| |-- branches
| |-- tags
| `-- trunk
| |-- module1
| | `-- pom.xml
| |-- moduleN
| | `-- pom.xml
| `-- pom.xml
`-- trunks
`-- pom.xml
This pom.xml
is a kind of "fake" pom: it is never released, it doesn't contain a real version since this file is never released, it only contains a list of modules. With this file, a checkout would result in this structure (pattern #3):
root/
parent-pom/
pom.xml
projectA/
pom.xml
This "hack" allows to launch of a reactor build from the root after a checkout and make things even more handy. Actually, this is how I like to setup maven projects and a VCS repository for large builds: it just works, it scales well, it gives all the flexibility you may need.
If the answer is no (back to the initial question), then I think you can live with pattern #1 (do the simplest thing that could possibly work).
Now, about the bonus questions:
- Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).
Honestly, I don't know how to not give a general answer here (like "use the level at which you think it makes sense to mutualize things"). And anyway, child poms can always override inherited settings.
- How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?
The setup I use works well, nothing particular to mention.
Actually, I wonder how the maven-release-plugin deals with pattern #1 (especially with the <parent>
section since you can't have SNAPSHOT dependencies at release time). This sounds like a chicken or egg problem but I just can't remember if it works and was too lazy to test it.
In addition to modifying your firewall, don't forget to add port binding too!
Open $(SolutionDir)\.vs\config\applicationHost.config
and find binding definitions, should be something like this
<sites>
<site name="Samples.Html5.Web" id="1">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="C:\Git\Samples.Html5.Web" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:63000:localhost" />
</bindings>
</site>
...
</sites>
Just add extra lines to reflect your machine IP and designated port
<bindings>
<binding protocol="http" bindingInformation="*:63000:localhost" />
<binding protocol="http" bindingInformation="*:63000:10.0.0.201" />
</bindings>
Source: https://blog.falafel.com/expose-iis-express-site-local-network/
In my case it was
Tools/Options/Debugging/General/Enable JavaScript debugging for ASP.NET (Chrome and IE)
Once I unchecked this, my debug start went from 45-60 seconds down to 0-5 seconds.
So, I know this is an old topic, but I'll first say it isn't possible. The closest thing currently is locking the mouse to a single position, and tracking change in its x and y. This concept has been adopted by - it looks like - Chrome and Firefox. It's managed by what's called Mouse Lock, and hitting escape will break it. From my brief read-up, I think the idea is that it locks the mouse to one location, and reports motion events similar to click-and-drag events.
Here's the release documentation:
FireFox: https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API
Chrome: http://www.chromium.org/developers/design-documents/mouse-lock
And here's a pretty neat demonstration: http://media.tojicode.com/q3bsp/
This can be done with cgroups, by combining knowledge from these two articles:
https://www.percona.com/blog/2015/07/01/using-cgroups-to-limit-mysql-and-mongodb-memory-usage/
http://frank2.net/cgroups-ubuntu-14-04/
You can find here a small shell script which will create config and init files for Ubuntu 14.04: http://brainsuckerna.blogspot.com.by/2016/05/limiting-mongodb-memory-usage-with.html
Just like that:
sudo bash -c 'curl -o- http://brains.by/misc/mongodb_memory_limit_ubuntu1404.sh | bash'
TL;DR:
git checkout HEAD path/to/file
git stash apply
Long version:
You get this error because of the uncommited changes that you want to overwrite. Undo these changes with git checkout HEAD
. You can undo changes to a specific file with git checkout HEAD path/to/file
. After removing the cause of the conflict, you can apply as usual.
make sure you don't have env variable NODE_ENV
set to 'production'.
If you do, dev dependencies will not be installed without the --dev
flag
Updated at 2016 : Pip
should already be included in Python 2.7.9+ or 3.4+
, but if for whatever reason it is not there, you can use the following one-liner.
python get-pip.py
(If you are on Linux, use sudo python get-pip.py
)PS:
This should already be satisfied in most cases but, if necessary, be sure that your environment variable PATH includes Python's folders (for example, Python 2.7.x
on Windows default install: C:\Python27 and C:\Python27\Scripts
, for Python 3.3x
: C:\Python33 and C:\Python33\Scripts
, etc)
I encounter same problem and then found such perhaps easiest way (one liner!) mentioned on official website here: http://www.pip-installer.org/en/latest/installing.html
Can't believe there are so many lengthy (perhaps outdated?) answers out there. Feeling thankful to them but, please up-vote this short answer to help more new comers!
Swift 5
Cant fetch data from your api.
Easiest way to parse json is Use Decodable
protocol. Or Codable
(Encodable & Decodable
).
For ex:
let json = """
{
"dueDate": {
"year": 2021,
"month": 2,
"day": 17
}
}
"""
struct WrapperModel: Codable {
var dueDate: DueDate
}
struct DueDate: Codable {
var year: Int
var month: Int
var day: Int
}
let jsonData = Data(json.utf8)
let decoder = JSONDecoder()
do {
let model = try decoder.decode(WrapperModel.self, from: jsonData)
print(model)
} catch {
print(error.localizedDescription)
}
You are getting an HTTP 400
(Bad Request) error because there is a space
in your URL. If you fix it (before the zoom
parameter), you will get an HTTP 400
error (Unauthorized).
Maybe you need some HTTP header to identify your download as a recognised browser (use the "User-Agent" header) or additional authentication parameter.
For the User-Agent example, then use the ImageIO.read(InputStream) using the connection inputstream:
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "xxxxxx");
Use whatever needed for xxxxxx
You can use jquery.form.js plugin to upload image via ajax to the server.
http://malsup.com/jquery/form/
Here is the sample jQuery ajax image upload script
(function() {
$('form').ajaxForm({
beforeSubmit: function() {
//do validation here
},
beforeSend:function(){
$('#loader').show();
$('#image_upload').hide();
},
success: function(msg) {
///on success do some here
}
}); })();
If you have any doubt, please refer following ajax image upload tutorial here
http://www.smarttutorials.net/ajax-image-upload-using-jquery-php-mysql/
Using there is another cool way to do this with Kotlin coroutines. The advantage of using a coroutine opposed to a Handler with a runnable (post/postDelayed) is that it does not fire up an expensive thread to execute a delayed action.
launch(UI){
delay(300)
scrollView.fullScroll(View.FOCUS_DOWN)
}
It is important to specify the coroutine's HandlerContext as UI otherwise the delayed action might not be called from the UI thread.
I came across this problem because my cols exceeded the row grid length (> 12)
A solution using 100% Bootstrap 4:
Since the rows in Bootstrap are already display: flex
You just need to add flex-fill
to the Col, and h-100
to the container and any children.
Pen here: https://codepen.io/joshkopecek/pen/Exjdgjo
<div class="container-fluid h-100">
<div class="row justify-content-center h-100">
<div class="col-4 hidden-md-down flex-fill" id="yellow">
XXXX
</div>
<div id="blue" class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8 h-100">
Form Goes Here
</div>
<div id="green" class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8 h-100">
Another form
</div>
</div>
</div>
Use getattr
if you have an attribute in string form:
>>> class User(object):
name = 'John'
>>> u = User()
>>> param = 'name'
>>> getattr(u, param)
'John'
Otherwise use the dot .
:
>>> class User(object):
name = 'John'
>>> u = User()
>>> u.name
'John'
Tryprint
Example:
print "Hello World!"
print
print "Hi!"
Hope this works!:)
By far the easiest solution is to just use the Google Chart API http://code.google.com/apis/chart/
You can make bar graphs, pie charts, use 3D, and it's as easy as building a url with some parameters. See the simple example below.
//By using jquery json parser
var obj = $.parseJSON('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(obj['jobtitel']);
//By using javasript json parser
var t = JSON.parse('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(t['jobtitel'])
As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.
Another solutions using vim (just for reference).
Solution 1:
Open file in vim vim filename
, then execute command :% normal Jj
This command is very easy to understand:
After that, save the file and exit with :wq
Solution 2:
Execute the command in shell, vim -c ":% normal Jj" filename
, then save the file and exit with :wq
.
In addition to Nick Craver's answer, for this to work properly on IE 8
you need to add a additional click handler to the checkbox:
// needed for IE 8 compatibility
if ($.browser.msie)
$("#myCheckbox").click(function() { $(this).trigger('change'); });
$("#myCheckbox").change( function() {
alert($(this).is(":checked"));
});
//Trigger by:
$("#myCheckbox").trigger('click').trigger('change');
Otherwise the callback will only be triggered when the checkbox loses focus, as IE 8
keeps focus on checkboxes and radios when they are clicked.
Haven't tested on IE 9
though.
Your cells object is not fully qualified. You need to add a DOT
before the cells object. For example
With Worksheets("Cable Cards")
.Range(.Cells(RangeStartRow, RangeStartColumn), _
.Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
Similarly, fully qualify all your Cells object.
Modern browsers now throw a security error for otherwise well-formed self-signed certificates if they are missing a SAN (Subject Alternate Name). OpenSSL does not provide a command-line way to specify this, so many developers' tutorials and bookmarks are suddenly outdated.
The quickest way to get running again is a short, stand-alone conf file:
Create an OpenSSL config file (example: req.cnf
)
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = US
ST = VA
L = SomeCity
O = MyCompany
OU = MyDivision
CN = www.company.com
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.company.com
DNS.2 = company.com
DNS.3 = company.net
Create the certificate referencing this config file
openssl req -x509 -nodes -days 730 -newkey rsa:2048 \
-keyout cert.key -out cert.pem -config req.cnf -sha256
Example config from https://support.citrix.com/article/CTX135602
Another valid option is to spread the joins across multiple LINQ clauses, as follows:
public static IEnumerable<Announcementboard> GetSiteContent(string pageName, DateTime date)
{
IEnumerable<Announcementboard> content = null;
IEnumerable<Announcementboard> addMoreContent = null;
try
{
content = from c in DB.Announcementboards
// Can be displayed beginning on this date
where c.Displayondate > date.AddDays(-1)
// Doesn't Expire or Expires at future date
&& (c.Displaythrudate == null || c.Displaythrudate > date)
// Content is NOT draft, and IS published
&& c.Isdraft == "N" && c.Publishedon != null
orderby c.Sortorder ascending, c.Heading ascending
select c;
// Get the content specific to page names
if (!string.IsNullOrEmpty(pageName))
{
addMoreContent = from c in content
join p in DB.Announceonpages on c.Announcementid equals p.Announcementid
join s in DB.Apppagenames on p.Apppagenameid equals s.Apppagenameid
where s.Apppageref.ToLower() == pageName.ToLower()
select c;
}
// Add the specified content using UNION
content = content.Union(addMoreContent);
// Exclude the duplicates using DISTINCT
content = content.Distinct();
return content;
}
catch (MyLovelyException ex)
{
// Add your exception handling here
throw ex;
}
}
Here is another way to loop through XML elements using JDOM.
List<Element> nodeNodes = inputNode.getChildren();
if (nodeNodes != null) {
for (Element nodeNode : nodeNodes) {
List<Element> elements = nodeNode.getChildren(elementName);
if (elements != null) {
elements.size();
nodeNodes.removeAll(elements);
}
}
Try:
String str = "my string \n my other string";
When printed you will get:
my string
my other string
I got the same error i created the app with create-react-app but in /public/index.html also added matrialize script but there was to connection with "root" so i added
<div id="root"></div>
just before
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/ materialize.min.js"></script>
And it worked for me .
One last thing to note, you may use the sys.intern
function to ensure that you're getting a reference to the same string:
>>> from sys import intern
>>> a = intern('a')
>>> a2 = intern('a')
>>> a is a2
True
As pointed out above, you should not be using is
to determine equality of strings. But this may be helpful to know if you have some kind of weird requirement to use is
.
Note that the intern
function used to be a builtin on Python 2 but was moved to the sys
module in Python 3.
http://htmldog.com/articles/superscript/ Essentially:
position: relative;
bottom: 0.5em;
font-size: 0.8em;
Works well in practice, as far as I can tell.
bad:
<a id="myLink" href="javascript:MyFunction();">link text</a>
good:
<a id="myLink" href="#" onclick="MyFunction();">link text</a>
better:
<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>
even better 1:
<a id="myLink" title="Click to do something"
href="#" onclick="MyFunction();return false;">link text</a>
even better 2:
<a id="myLink" title="Click to do something"
href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">link text</a>
Why better? because return false
will prevent browser from following the link
best:
Use jQuery or other similar framework to attach onclick handler by element's ID.
$('#myLink').click(function(){ MyFunction(); return false; });
Most of it is explained in the GC Tuning Guide (which you would do well to read anyway).
The command line option
-verbose:gc
causes information about the heap and garbage collection to be printed at each collection. For example, here is output from a large server application:[GC 325407K->83000K(776768K), 0.2300771 secs] [GC 325816K->83372K(776768K), 0.2454258 secs] [Full GC 267628K->83769K(776768K), 1.8479984 secs]
Here we see two minor collections followed by one major collection. The numbers before and after the arrow (e.g.,
325407K->83000K
from the first line) indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the size includes some objects that are garbage (no longer alive) but that cannot be reclaimed. These objects are either contained in the tenured generation, or referenced from the tenured or permanent generations.The next number in parentheses (e.g.,
(776768K)
again from the first line) is the committed size of the heap: the amount of space usable for java objects without requesting more memory from the operating system. Note that this number does not include one of the survivor spaces, since only one can be used at any given time, and also does not include the permanent generation, which holds metadata used by the virtual machine.The last item on the line (e.g.,
0.2300771 secs
) indicates the time taken to perform the collection; in this case approximately a quarter of a second.The format for the major collection in the third line is similar.
The format of the output produced by
-verbose:gc
is subject to change in future releases.
I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?
Use \def
command:
\def \variable {Something that's better to use as a variable}
Be aware that \def
overrides preexisting macros without any warnings and therefore can cause various subtle errors. To overcome this either use namespaced variables like my_var
or fall back to \newcommand
, \renewcommand
commands instead.
I happened to have to set up Apache & PHP on two laptops recently. After much weeping and gnashing of teeth, I noticed in phpinfo's output that (for whatever reason: not paying attention during PHP install, bad installer) Apache expected php.ini to be somewhere where it wasn't.
Two choices:
... and restart Apache. Timezone settings should be recognized at that point.
:set list
in Vim will show whitespace. End of lines show as '$
' and carriage returns usually show as '^M
'.
Here is some LESS for you, in case you customize the navbar:
.navbar .divider-vertical {
height: floor(@navbar-height - @navbar-margin-bottom);
margin: floor(@navbar-margin-bottom / 2) 9px;
border-left: 1px solid #f2f2f2;
border-right: 1px solid #ffffff;
}
Here is filter
with Underscore library might help you, we remove item with name "ted"
$scope.items = _.filter($scope.items, function(item) {
return !(item.name == 'ted');
});
e.g.:
CREATE
, ALTER
, DROP
, TRUNCATE
, COMMIT
, etc.DML statement are affect on table. So that is the basic operations we perform in a table.
SELECT
, INSERT
, UPDATE
, etc.Below Commands are used in DML:
INSERT
, UPDATE
, SELECT
, DELETE
, etc.for ((i=0; i<=1000; i++)); do
echo "http://example.com/$i.jpg"
done
Of course, just assign seperate css classes to both tables.
<table class="style1"></table>
<table class="style2"></table>
.css
table.style1 { //your css here}
table.style2 { //your css here}
pip install weasyprint # No longer supports Python 2.x.
python
>>> import weasyprint
>>> pdf = weasyprint.HTML('http://www.google.com').write_pdf()
>>> len(pdf)
92059
>>> open('google.pdf', 'wb').write(pdf)
You can use the dangerouslySetInnerHTML
property to inject arbitrary HTML:
// Assume from another require()'ed module:_x000D_
var html = '<h1>Hello, world!</h1>'_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
render: function() {_x000D_
return React.createElement("h1", {dangerouslySetInnerHTML: {__html: html}})_x000D_
}_x000D_
})_x000D_
_x000D_
ReactDOM.render(React.createElement(MyComponent), document.getElementById('app'))
_x000D_
<script src="https://fb.me/react-0.14.3.min.js"></script>_x000D_
<script src="https://fb.me/react-dom-0.14.3.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
You could even componentize this template behavior (untested):
class TemplateComponent extends React.Component {
constructor(props) {
super(props)
this.html = require(props.template)
}
render() {
return <div dangerouslySetInnerHTML={{__html: this.html}}/>
}
}
TemplateComponent.propTypes = {
template: React.PropTypes.string.isRequired
}
// use like
<TemplateComponent template='./template.html'/>
And with this, template.html
(in the same directory) looks something like (again, untested):
// ./template.html
module.exports = '<h1>Hello, world!</h1>'
If you always return JSON from the server (no empty responses), dataType: 'json'
should work and contentType
is not needed. However make sure the JSON output...
jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!
I needed a non-interactive method for cloning a private repo.
Inspired by this issue: https://github.com/github/hub/issues/1644
Step 1.
Create a personal access token in the github developer settings: https://github.com/settings/tokens
Step 2.
git clone https://$token:[email protected]/$username/$repo.git
In datasets having large number of columns its even better to see how many columns contain null values and how many don't.
print("No. of columns containing null values")
print(len(df.columns[df.isna().any()]))
print("No. of columns not containing null values")
print(len(df.columns[df.notna().all()]))
print("Total no. of columns in the dataframe")
print(len(df.columns))
For example in my dataframe it contained 82 columns, of which 19 contained at least one null value.
Further you can also automatically remove cols and rows depending on which has more null values
Here is the code which does this intelligently:
df = df.drop(df.columns[df.isna().sum()>len(df.columns)],axis = 1)
df = df.dropna(axis = 0).reset_index(drop=True)
Note: Above code removes all of your null values. If you want null values, process them before.
way of foreign key creation correct for ActiveDirectories(id), i think the main mistake is you didn't mentioned primary key for id in ActiveDirectories table
You can use Ctrl + M and Ctrl + P
It's called Edit.StopOutlining
After all files have been added, the next step is a "git commit".
"git status" will suggest what to do: files yet to add are listed at the bottom, and once they are all done, it will suggest a commit at the top, where it explains the merge status of the current branch.
int div3(int x)
{
int reminder = abs(x);
int result = 0;
while(reminder >= 3)
{
result++;
reminder--;
reminder--;
reminder--;
}
return result;
}
Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
I believe you are trying to compare two strings representing values, the function you are looking for is:
int atoi(const char *nptr);
or
long int strtol(const char *nptr, char **endptr, int base);
these functions will allow you to convert a string to an int/long int:
int val = strtol("555", NULL, 10);
and compare it to another value.
int main (int argc, char *argv[])
{
long int val = 0;
if (argc < 2)
{
fprintf(stderr, "Usage: %s number\n", argv[0]);
exit(EXIT_FAILURE);
}
val = strtol(argv[1], NULL, 10);
printf("%d is %s than 555\n", val, val > 555 ? "bigger" : "smaller");
return 0;
}
Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.
Look below at the working code. Copy and paste it.
import (
"bytes"
"encoding/json" // Encoding and Decoding Package
"fmt"
)
var messeging = `{
"say":"Hello",
"sendMsg":{
"user":"ANisus",
"msg":"Trying to send a message"
}
}`
type SendMsg struct {
User string `json:"user"`
Msg string `json:"msg"`
}
type Chat struct {
Say string `json:"say"`
SendMsg *SendMsg `json:"sendMsg"`
}
func main() {
/** Clean way to solve Json Decoding in Go */
/** Excellent solution */
var chat Chat
r := bytes.NewReader([]byte(messeging))
chatErr := json.NewDecoder(r).Decode(&chat)
errHandler(chatErr)
fmt.Println(chat.Say)
fmt.Println(chat.SendMsg.User)
fmt.Println(chat.SendMsg.Msg)
}
func errHandler(err error) {
if err != nil {
fmt.Println(err)
return
}
}
There are some inconsistencies in how browsers expose the current window scrolling coordinates. Google Chrome on Mac and iOS seems to always return 0
when using document.documentElement.scrollTop
or jQuery's $(window).scrollTop()
.
However, it works consistently with:
// horizontal scrolling amount
window.pageXOffset
// vertical scrolling amount
window.pageYOffset
As the message says:
no changes added to commit (use "git add" and/or "git commit -a")
Git has a "staging area" where files need to be added before being committed, you can read an explanation of it here.
For your specific example, you can use:
git commit -am "save arezzo files"
(note the extra a
in the flags, can also be written as git commit -a -m "message"
- both do the same thing)
Alternatively, if you want to be more selective about what you add to the commit, you use the git add command to add the appropriate files to the staging area, and git status to preview what is about to be added (remembering to pay attention to the wording used).
You can also find general documentation and tutorials for how to use git on the git documentation page which will give more detail about the concept of staging/adding files.
One other thing worth knowing about is interactive staging - this allows you to add parts of a file to the staging area, so if you've made three distinct code changes (for related but different functionality), you can use interactive mode to split the changes and add/commit each part in turn. Having smaller specific commits like this can be helpful.
In addition to what provided in the other answers, the keyword "zorder" allows one to decide the order in which different objects are plotted vertically. E.g.:
plt.plot(x,y,zorder=1)
plt.scatter(x,y,zorder=2)
plots the scatter symbols on top of the line, while
plt.plot(x,y,zorder=2)
plt.scatter(x,y,zorder=1)
plots the line over the scatter symbols.
See, e.g., the zorder demo
Check the service name of a database by
sql> show parameter service;
You can create simple float-based forms without having to lose your liquid layout. For example:
<style type="text/css">
.row { clear: left; padding: 6px; }
.row label { float: left; width: 10em; }
.row .field { display: block; margin-left: 10em; }
.row .field input, .row .field select {
width: 100%;
box-sizing: border-box;
-moz-box-sizing: border-box; -webkit-box-sizing: border-box; -khtml-box-sizing: border-box;
}
</style>
<div class="row">
<label for="f-firstname">First name</label>
<span class="field"><input name="firstname" id="f-firstname" value="Bob" /></span>
</div>
<div class="row">
<label for="f-state">State</label>
<span class="field"><select name="state" id="f-state">
<option value="NY">NY</option>
</select></span>
</div>
This does tend to break down, though, when you have complex form layouts where there's a grid of multiple fixed and flexible width columns. At that point you have to decide whether to stick with divs and abandon liquid layout in favour of just dropping everything into fixed pixel positions, or let tables do it.
For me personally, liquid layout is a more important usability feature than the exact elements used to lay out the form, so I usually go for tables.
I did not get the accepted answer to work, but this seems to do the trick, at least in vanilla JS.
if(e.target !== e.currentTarget) return;
In regards to PowerShell 5.1 (this is so much easier in PowerShell 7)...
Operating off the assumption that we have a file named jsonConfigFile.json
with the following content from your post:
{
"Stuffs": [
{
"Name": "Darts",
"Type": "Fun Stuff"
},
{
"Name": "Clean Toilet",
"Type": "Boring Stuff"
}
]
}
This will create an ordered hashtable from a JSON file to help make retrieval easier:
$json = [ordered]@{}
(Get-Content "jsonConfigFile.json" -Raw | ConvertFrom-Json).PSObject.Properties |
ForEach-Object { $json[$_.Name] = $_.Value }
$json.Stuffs
will list a nice hashtable, but it gets a little more complicated from here. Say you want the Type
key's value associated with the Clean Toilet
key, you would retrieve it like this:
$json.Stuffs.Where({$_.Name -eq "Clean Toilet"}).Type
It's a pain in the ass, but if your goal is to use JSON on a barebones Windows 10 installation, this is the best way to do it as far as I've found.
adb -d shell
(or adb -e shell
).
This command will help you in most of the cases, if you are too lazy to type the full ID.
From http://developer.android.com/tools/help/adb.html#commandsummary:
-d
- Direct an adb command to the only attached USB device. Returns an error when more than one USB device is attached.
-e
- Direct an adb command to the only running emulator. Returns an error when more than one emulator is running.
As of now (NOV-2019), graph.api V5.0
graph API says, refer graph api
A link to the person's Timeline. The link will only resolve if the person clicking the link is logged into Facebook and is a friend of the person whose profile is being viewed.
I had a span that would create a popup. If I used "click touchstart" it would trigger parts of the popup during the touchend. I fixed this by making the span "click touchend".
You could create your own script for running ant, e.g. named ant.sh like:
#!/bin/sh
JAVA_HOME=</path/to/jdk>; export JAVA_HOME
ant $@
and then run your script.
$ chmod 755 ant.sh
$./ant.sh clean compile
or whatever ant target you wish to run
You can use this configuration for cuda 10.0 (10.1 does not work as of 3/18), this runs for me:
Install version tensorflow gpu:
pip install tensorflow-gpu==1.4.0
h/H = 12/24 hours means you will write hh:mm = 12 hours format and HH:mm = 24 hours format
you can use str_replace
say your name is in variable $name
$result = str_replace(' ', '_', $name);
another way is to use regex, as it will help to eliminate 2-time space etc.
$result= preg_replace('/\s+/', '_', $name);
String.equalsIgnoreCase
is the most practical choice for naive case-insensitive string comparison.
However, it is good to be aware that this method does neither do full case folding nor decomposition and so cannot perform caseless matching as specified in the Unicode standard. In fact, the JDK APIs do not provide access to information about case folding character data, so this job is best delegated to a tried and tested third-party library.
That library is ICU, and here is how one could implement a utility for case-insensitive string comparison:
import com.ibm.icu.text.Normalizer2;
// ...
public static boolean equalsIgnoreCase(CharSequence s, CharSequence t) {
Normalizer2 normalizer = Normalizer2.getNFKCCasefoldInstance();
return normalizer.normalize(s).equals(normalizer.normalize(t));
}
String brook = "?u\u0308ßchen";
String BROOK = "FLÜSSCHEN";
assert equalsIgnoreCase(brook, BROOK);
Naive comparison with String.equalsIgnoreCase
, or String.equals
on upper- or lowercased strings will fail even this simple test.
(Do note though that the predefined case folding flavour getNFKCCasefoldInstance
is locale-independent; for Turkish locales a little more work involving UCharacter.foldCase
may be necessary.)
No. Actually out
is a static member in the System
class (not as in .NET), being an instance of PrintStream
. And println
is a normal (overloaded) method of the PrintStream
class.
See http://download.oracle.com/javase/6/docs/api/java/lang/System.html#out.
Actually, if out
/err
/in
were classes, they would be named with capital character (Out
/Err
/In
) due to the naming convention (ignoring grammar).
What to do if :foo
in its natural form contains slashes? You wouldn't want it to Isn't that the distinction the recommendation is attempting to preserve? It specifically notes,
The similarity to unix and other disk operating system filename conventions should be taken as purely coincidental, and should not be taken to indicate that URIs should be interpreted as file names.
If one was building an online interface to a backup program, and wished to express the path as a part of the URL path, it would make sense to encode the slashes in the file path, as that is not really part of the hierarchy of the resource - and more importantly, the route. /backups/2016-07-28content//home/dan/
loses the root of the filesystem in the double slash. Escaping the slashes is the appropriate way to distinguish, as I read it.
It's an unportable way to remove all data from the input buffer till the next newline. I've seen it used in cases like that:
char c;
char s[32];
puts("Type a char");
c=getchar();
fflush(stdin);
puts("Type a string");
fgets(s,32,stdin);
Without the fflush()
, if you type a character, say "a", and the hit enter, the input buffer contains "a\n", the getchar()
peeks the "a", but the "\n" remains in the buffer, so the next fgets()
will find it and return an empty string without even waiting for user input.
However, note that this use of fflush()
is unportable. I've tested right now on a Linux machine, and it does not work, for example.
If you want, you can add throws clauses to your methods. Then you don't have to catch checked methods right away. That way, you can catch the exceptions
later (perhaps at the same time as other exceptions
).
The code looks like:
public void someMethode() throws SomeCheckedException {
// code
}
Then later you can deal with the exceptions
if you don't wanna deal with them in that method.
To catch all exceptions some block of code may throw you can do: (This will also catch Exceptions
you wrote yourself)
try {
// exceptional block of code ...
// ...
} catch (Exception e){
// Deal with e as you please.
//e may be any type of exception at all.
}
The reason that works is because Exception
is the base class for all exceptions. Thus any exception that may get thrown is an Exception
(Uppercase 'E').
If you want to handle your own exceptions first simply add a catch
block before the generic Exception one.
try{
}catch(MyOwnException me){
}catch(Exception e){
}
Using the browser's parser is the probably the best bet in current browsers. The following will work, with the following caveats:
<div>
element. HTML contained within <body>
or <html>
or <head>
tags is not valid within a <div>
and may therefore not be parsed correctly.textContent
(the DOM standard property) and innerText
(non-standard) properties are not identical. For example, textContent
will include text within a <script>
element while innerText
will not (in most browsers). This only affects IE <=8, which is the only major browser not to support textContent
.<script>
elements.null
<img onerror='alert(\"could run arbitrary JS here\")' src=bogus>
Code:
var html = "<p>Some HTML</p>";
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";
Even though I realise this is an old question, I'd like to suggest using the traceback
module to handle output of the exceptions.
Use traceback.print_exc()
to print the current exception to standard error, just like it would be printed if it remained uncaught, or traceback.format_exc()
to get the same output as a string. You can pass various arguments to either of those functions if you want to limit the output, or redirect the printing to a file-like object.
A lazy val is most easily understood as a "memoized (no-arg) def".
Like a def, a lazy val is not evaluated until it is invoked. But the result is saved so that subsequent invocations return the saved value. The memoized result takes up space in your data structure, like a val.
As others have mentioned, the use cases for a lazy val are to defer expensive computations until they are needed and store their results, and to solve certain circular dependencies between values.
Lazy vals are in fact implemented more or less as memoized defs. You can read about the details of their implementation here:
http://docs.scala-lang.org/sips/pending/improved-lazy-val-initialization.html
+1 to @MartinNuc, you can run the mysql
client in batch mode and then you won't see the long stream of "OK" lines.
The amount of time it takes to import a given SQL file depends on a lot of things. Not only the size of the file, but the type of statements in it, how powerful your server server is, and how many other things are running at the same time.
@MartinNuc says he can load 4GB of SQL in 4-5 minutes, but I have run 0.5 GB SQL files and had it take 45 minutes on a smaller server.
We can't really guess how long it will take to run your SQL script on your server.
Re your comment,
@MartinNuc is correct you can choose to make the mysql client print every statement. Or you could open a second session and run mysql> SHOW PROCESSLIST
to see what's running. But you probably are more interested in a "percentage done" figure or an estimate for how long it will take to complete the remaining statements.
Sorry, there is no such feature. The mysql client doesn't know how long it will take to run later statements, or even how many there are. So it can't give a meaningful estimate for how much time it will take to complete.
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.Toast;
public class imageDownload {
Bitmap bmImg;
void downloadfile(String fileurl,ImageView img)
{
URL myfileurl =null;
try
{
myfileurl= new URL(fileurl);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
try
{
HttpURLConnection conn= (HttpURLConnection)myfileurl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
bmImg = BitmapFactory.decodeStream(is,null,options);
img.setImageBitmap(bmImg);
//dialog.dismiss();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
// Toast.makeText(PhotoRating.this, "Connection Problem. Try Again.", Toast.LENGTH_SHORT).show();
}
}
}
in your activity take imageview & set resource imageDownload(url,yourImageview);
Here is the code with line 156, it has try and catch above it
/// <summary>
/// Execute a SQL Query statement, using the default SQL connection for the application
/// </summary>
/// <param name="query">SQL query to execute</param>
/// <returns>DataTable of results</returns>
public static DataTable Query(string query)
{
DataTable results = new DataTable();
string configConnectionString = "ApplicationServices";
System.Configuration.Configuration WebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/Web.config");
System.Configuration.ConnectionStringSettings connString;
if (WebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString = WebConfig.ConnectionStrings.ConnectionStrings[configConnectionString];
if (connString != null)
{
try
{
using (SqlConnection conn = new SqlConnection(connString.ToString()))
using (SqlCommand cmd = new SqlCommand(query, conn))
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
dataAdapter.Fill(results);
return results;
}
catch (Exception ex)
{
throw new SqlException(string.Format("SqlException occurred during query execution: ", ex));
}
}
else
{
throw new SqlException(string.Format("Connection string for " + configConnectionString + "is null."));
}
}
else
{
throw new SqlException(string.Format("No connection strings found in Web.config file."));
}
}
Don't hardcode the character encoding of your environment inside your script; print Unicode text directly instead:
assert isinstance(text, unicode) # or str on Python 3
print(text)
If your output is redirected to a file (or a pipe); you could use PYTHONIOENCODING
envvar, to specify the character encoding:
$ PYTHONIOENCODING=utf-8 python your_script.py >output.utf8
Otherwise, python your_script.py
should work as is -- your locale settings are used to encode the text (on POSIX check: LC_ALL
, LC_CTYPE
, LANG
envvars -- set LANG
to a utf-8 locale if necessary).
I have writen a single file AJAX tester. Enjoy it!!! Just because I have had problems with my hosting provider
<?php /*
Author: Luis Siquot
Purpose: Check ajax performance and errors
License: GPL
site5: Please don't drop json requests (nor delay)!!!!
*/
$r = (int)$_GET['r'];
$w = (int)$_GET['w'];
if($r) {
sleep($w);
echo json_encode($_GET);
die ();
} //else
?><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var _settimer;
var _timer;
var _waiting;
$(function(){
clearTable();
$('#boton').bind('click', donow);
})
function donow(){
var w;
var estim = 0;
_waiting = $('#total')[0].value * 1;
clearTable();
for(var r=1;r<=_waiting;r++){
w = Math.floor(Math.random()*6)+2;
estim += w;
dodebug({r:r, w:w});
$.ajax({url: '<?php echo $_SERVER['SCRIPT_NAME']; ?>',
data: {r:r, w:w},
dataType: 'json', // 'html',
type: 'GET',
success: function(CBdata, status) {
CBdebug(CBdata);
}
});
}
doStat(estim);
timer(estim+10);
}
function doStat(what){
$('#stat').replaceWith(
'<table border="0" id="stat"><tr><td>Request Time Sum=<th>'+what+
'<td> /2=<th>'+Math.ceil(what/2)+
'<td> /3=<th>'+Math.ceil(what/3)+
'<td> /4=<th>'+Math.ceil(what/4)+
'<td> /6=<th>'+Math.ceil(what/6)+
'<td> /8=<th>'+Math.ceil(what/8)+
'<td> (seconds)</table>'
);
}
function timer(what){
if(what) {_timer = 0; _settimer = what;}
if(_waiting==0) {
$('#showTimer')[0].innerHTML = 'completed in <b>' + _timer + ' seconds</b> (aprox)';
return ;
}
if(_timer<_settimer){
$('#showTimer')[0].innerHTML = _timer;
setTimeout("timer()",1000);
_timer++;
return;
}
$('#showTimer')[0].innerHTML = '<b>don\'t wait any more!!!</b>';
}
function CBdebug(what){
_waiting--;
$('#req'+what.r)[0].innerHTML = 'x';
}
function dodebug(what){
var tt = '<tr><td>' + what.r + '<td>' + what.w + '<td id=req' + what.r + '> '
$('#debug').append(tt);
}
function clearTable(){
$('#debug').replaceWith('<table border="1" id="debug"><tr><td>Request #<td>Wait Time<td>Done</table>');
}
</script>
</head>
<body>
<center>
<input type="button" value="start" id="boton">
<input type="text" value="80" id="total" size="2"> concurrent json requests
<table id="stat"><tr><td> </table>
Elapsed Time: <span id="showTimer"></span>
<table id="debug"></table>
</center>
</body>
Edit:
r means row and w waiting time.
When you initially press start button 80 (or any other number) of concurrent ajax request are launched by javascript, but as is known they are spooled by the browser. Also they are requested to the server in parallel (limited to certain number, this is the fact of this question). Here the requests are solved server side with a random delay (established by w). At start time all the time needed to solve all ajax calls is calculated. When test is finished, you can see if it took half, took third, took a quarter, etc of the total time, deducting which was the parallelism on the calls to the server. This is not strict, nor precise, but is nice to see in real time how ajaxs calls are completed (seeing the incoming cross). And is a very simple self contained script to show ajax basics.
Of course, this assumes, that server side is not introducing any extra limit.
Preferably use in conjunction with firebug net panel (or your browser's equivalent)
except Michael Anderson's answer, i have coding with other two way in my project.
you can white all variable to one class. created a kotlin file named Const
object Const {
const val FIRST_NAME_1 = "just"
const val LAST_NAME_1 = "YuMu"
}
You can use it in kotlin and java code
Log.d("stackoverflow", Const.FIRST_NAME_1)
You can use Kotlin's extension function
created a kotlin file named Ext, below code is the all code in Ext file
package pro.just.yumu
/**
* Created by lpf on 2020-03-18.
*/
const val FIRST_NAME = "just"
const val LAST_NAME = "YuMu"
You can use it in kotlin code
Log.d("stackoverflow", FIRST_NAME)
You can use it in java code
Log.d("stackoverflow", ExtKt.FIRST_NAME);
Here's one way to do this through the console:
>> foo = ActionView::Base.new
=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>
>> foo.extend YourHelperModule
=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>
>> foo.your_helper_method(args)
=> "<html>created by your helper</html>"
Creating a new instance of ActionView::Base
gives you access to the normal view methods that your helper likely uses. Then extending YourHelperModule
mixes its methods into your object letting you view their return values.
Check this out:
wget https://raw.githubusercontent.com/circulosmeos/gdown.pl/master/gdown.pl
chmod +x gdown.pl
./gdown.pl https://drive.google.com/file/d/FILE_ID/view TARGET_PATH
To find a class in a folder (and subfolders) bunch of JARs: https://jarscan.com/
Usage: java -jar jarscan.jar [-help | /?]
[-dir directory name]
[-zip]
[-showProgress]
<-files | -class | -package>
<search string 1> [search string 2]
[search string n]
Help:
-help or /? Displays this message.
-dir The directory to start searching
from default is "."
-zip Also search Zip files
-showProgress Show a running count of files read in
-files or -class Search for a file or Java class
contained in some library.
i.e. HttpServlet
-package Search for a Java package
contained in some library.
i.e. javax.servlet.http
search string The file or package to
search for.
i.e. see examples above
Example:
java -jar jarscan.jar -dir C:\Folder\To\Search -showProgress -class GenericServlet
Suppose you want to add those flags (better to declare them in a constant):
SET(GCC_COVERAGE_COMPILE_FLAGS "-fprofile-arcs -ftest-coverage")
SET(GCC_COVERAGE_LINK_FLAGS "-lgcov")
There are several ways to add them:
The easiest one (not clean, but easy and convenient, and works only for compile flags, C & C++ at once):
add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})
Appending to corresponding CMake variables:
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}")
Using target properties, cf. doc CMake compile flag target property and need to know the target name.
get_target_property(TEMP ${THE_TARGET} COMPILE_FLAGS)
if(TEMP STREQUAL "TEMP-NOTFOUND")
SET(TEMP "") # Set to empty string
else()
SET(TEMP "${TEMP} ") # A space to cleanly separate from existing content
endif()
# Append our values
SET(TEMP "${TEMP}${GCC_COVERAGE_COMPILE_FLAGS}" )
set_target_properties(${THE_TARGET} PROPERTIES COMPILE_FLAGS ${TEMP} )
Right now I use method 2.
char[] characters;
...
string s = new string(characters);
DONE.
Example whatever.h
#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif
Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once
but it is not guaranteed to be supported on every compiler.
Example whatever.c
#include "whatever.h"
int f(int a) { return a + 1; }
And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.
Like this:
sample.c
#include "whatever.h"
int main(int argc, char **argv)
{
printf("%d\n", f(2)); /* prints 3 */
return 0;
}
To compile it (if you use GCC):
$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o
To link the files to create an executable file:
$ gcc sample.o whatever.o -o sample
You can test sample:
$ ./sample
3
$
for ($s=65; $s<=90; $s++) {
//echo chr($s);
$objPHPExcel->getActiveSheet()->getColumnDimension(chr($s))->setAutoSize(true);
}
%>%
is similar to pipe in Unix. For example, in
a <- combined_data_set %>% group_by(Outlet_Identifier) %>% tally()
the output of combined_data_set
will go into group_by
and its output will go into tally
, then the final output is assigned to a
.
This gives you handy and easy way to use functions in series without creating variables and storing intermediate values.
Take a look at http://start.spring.io/ it basically gives you a kick starter with either maven or gradle build.
Note: This is a Spring Boot based archetype.
I have a slightly different approach that might be useful/more beneficial to some.
Under your main project folder, create a resource folder. Your folder structure should look something like this.
Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.
Under categories on the left side, select Sources.
In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.
You should now be able to pull resources using this line or similar approach:
MyClass.class.getResource("/main.jpg");
If you were to create a package called Images under the resources folder, you can retrieve the resource like this:
MyClass.class.getResource("/Images/main.jpg");
Example of a Boolean (AND) plus Wildcard search, which I'm using inside a javascript Autocomplete plugin:
String to match: "my word"
String to search: "I'm searching for my funny words inside this text"
You need the following regex: /^(?=.*my)(?=.*word).*$/im
Explaining:
^ assert position at start of a line
?= Positive Lookahead
.* matches any character (except newline)
() Groups
$ assert position at end of a line
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
Test the Regex here: https://regex101.com/r/iS5jJ3/1
So, you can create a javascript function that:
Example:
function fullTextCompare(myWords, toMatch){_x000D_
//Replace regex reserved characters_x000D_
myWords=myWords.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');_x000D_
//Split your string at spaces_x000D_
arrWords = myWords.split(" ");_x000D_
//Encapsulate your words inside regex groups_x000D_
arrWords = arrWords.map(function( n ) {_x000D_
return ["(?=.*"+n+")"];_x000D_
});_x000D_
//Create a regex pattern_x000D_
sRegex = new RegExp("^"+arrWords.join("")+".*$","im");_x000D_
//Execute the regex match_x000D_
return(toMatch.match(sRegex)===null?false:true);_x000D_
}_x000D_
_x000D_
//Using it:_x000D_
console.log(_x000D_
fullTextCompare("my word","I'm searching for my funny words inside this text")_x000D_
);_x000D_
_x000D_
//Wildcards:_x000D_
console.log(_x000D_
fullTextCompare("y wo","I'm searching for my funny words inside this text")_x000D_
);
_x000D_
This is the job for style
property:
document.getElementById("remember").style.visibility = "visible";
if your application uses threads directly or indirectly (i.e. behind the scene like in a 3rd-party library) it is absolutely common to have threads terminate after they are done... which is basically what you describe... the debugger shows this message... you can configure the debugger to not display this message if you don't want it...
If the above does not help then please provide more details since I am not sure what exactly the problem is you face...
Here is another drawable xml for those who want to add all together gradient background, corner radius and ripple effect:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/colorPrimaryDark">
<item android:id="@android:id/mask">
<shape android:shape="rectangle">
<solid android:color="@color/colorPrimaryDark" />
<corners android:radius="@dimen/button_radius_large" />
</shape>
</item>
<item android:id="@android:id/background">
<shape android:shape="rectangle">
<gradient
android:angle="90"
android:endColor="@color/colorPrimaryLight"
android:startColor="@color/colorPrimary"
android:type="linear" />
<corners android:radius="@dimen/button_radius_large" />
</shape>
</item>
</ripple>
Add this to the background of your button.
<Button
...
android:background="@drawable/button_background" />
PS: this answer works for android api 21 and above.
I use this function to convert an string[][]
to a csv file. It quotes a cell, if it contains a "
, a ,
or other whitespace (except blanks):
/**
* Takes an array of arrays and returns a `,` sparated csv file.
* @param {string[][]} table
* @returns {string}
*/
function toCSV(table) {
return table
.map(function(row) {
return row
.map(function(cell) {
// We remove blanks and check if the column contains
// other whitespace,`,` or `"`.
// In that case, we need to quote the column.
if (cell.replace(/ /g, '').match(/[\s,"]/)) {
return '"' + cell.replace(/"/g, '""') + '"';
}
return cell;
})
.join(',');
})
.join('\n'); // or '\r\n' for windows
}
Note: does not work on Internet Explorer < 11 unless map
is polyfilled.
Note: If the cells contain numbers, you can add cell=''+cell
before if (cell.replace...
to convert numbers to strings.
Or you can write it in one line using ES6:
t.map(r=>r.map(c=>c.replace(/ /g, '').match(/[\s,"]/)?'"'+c.replace(/"/g,'""')+'"':c).join(',')).join('\n')
I had something similar and got it to work by effectively adding some padding-top to the child.
I'm sure some of the other answers here would get to the solution, but I couldn't get them to easily work after a lot of time; I instead ended up with the padding-top solution which is elegant in its simplicity, but seems kind of hackish to me (not to mention the pixel value it sets would probably depend on the parent height).
Here is a one-liner using ES6 arrow functions.
const sumPropertyValue = (items, prop) => items.reduce((a, b) => a + b[prop], 0);
// usage:
const cart_items = [ {quantity: 3}, {quantity: 4}, {quantity: 2} ];
const cart_total = sumPropertyValue(cart_items, 'quantity');
I found I could improve the situation a little with CSS dedicated to Webkit (Safari, Chrome). However, I had to set a fixed width and height on the field because the font change will resize the field.
@media screen and (-webkit-min-device-pixel-ratio:0){ /* START WEBKIT */
INPUT[type="password"]{
font-family:Verdana,sans-serif;
height:28px;
font-size:19px;
width:223px;
padding:5px;
}
} /* END WEBKIT */
Simplest is actually just Age.Max()
, you don't need any more code.
Try this-
CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
insert into student (name,user_name,branch) values (name ,user_name,branch);
END
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
This is my 2 cents based on Grax's answer, but with two parameters required for a generic method.
Assume your method is defined as follows in an Helpers class:
public class Helpers
{
public static U ConvertCsvDataToCollection<U, T>(string csvData)
where U : ObservableCollection<T>
{
//transform code here
}
}
In my case, U type is always an observable collection storing object of type T.
As I have my types predefined, I first create the "dummy" objects that represent the observable collection (U) and the object stored in it (T) and that will be used below to get their type when calling the Make
object myCollection = Activator.CreateInstance(collectionType);
object myoObject = Activator.CreateInstance(objectType);
Then call the GetMethod to find your Generic function:
MethodInfo method = typeof(Helpers).
GetMethod("ConvertCsvDataToCollection");
So far, the above call is pretty much identical as to what was explained above but with a small difference when you need have to pass multiple parameters to it.
You need to pass an Type[] array to the MakeGenericMethod function that contains the "dummy" objects' types that were create above:
MethodInfo generic = method.MakeGenericMethod(
new Type[] {
myCollection.GetType(),
myObject.GetType()
});
Once that's done, you need to call the Invoke method as mentioned above.
generic.Invoke(null, new object[] { csvData });
And you're done. Works a charm!
UPDATE:
As @Bevan highlighted, I do not need to create an array when calling the MakeGenericMethod function as it takes in params and I do not need to create an object in order to get the types as I can just pass the types directly to this function. In my case, since I have the types predefined in another class, I simply changed my code to:
object myCollection = null;
MethodInfo method = typeof(Helpers).
GetMethod("ConvertCsvDataToCollection");
MethodInfo generic = method.MakeGenericMethod(
myClassInfo.CollectionType,
myClassInfo.ObjectType
);
myCollection = generic.Invoke(null, new object[] { csvData });
myClassInfo contains 2 properties of type Type
which I set at run time based on an enum value passed to the constructor and will provide me with the relevant types which I then use in the MakeGenericMethod.
Thanks again for highlighting this @Bevan.
Sysinternals has another tool you could use, Strings.exe
Example:
strings.exe c:\windows\system32\wuauclt.exe > %temp%\wuauclt_strings.txt && %temp%\wuauclt_strings.txt
You can try this:
td p {word-break:break-all;}
This, however, makes it appear like this when there's enough space, unless you add a <br>
tag:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
So, I would then suggest adding <br>
tags where there are newlines, if possible.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Also, if this doesn't solve your problem, there's a similar thread here.
Alternate solution
Create a column that will store the month:
data['month'] = data['date'].dt.month
Create a column that will store the year:
data['year'] = data['date'].dt.year
[Personal Option] Avoiding using $scope, based on John Papa Angular Style Guide
so my idea is take advantage of the current model:
(function(){_x000D_
'use strict';_x000D_
_x000D_
var app = angular.module('way', [])_x000D_
app.controller('Decision', Decision);_x000D_
_x000D_
Decision.$inject = []; _x000D_
_x000D_
function Decision(){_x000D_
var vm = this;_x000D_
vm.checkItOut = _register;_x000D_
_x000D_
function _register(newOption){_x000D_
console.log('should I stay or should I go');_x000D_
console.log(newOption); _x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
})();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div ng-app="way">_x000D_
<div ng-controller="Decision as vm">_x000D_
<form name="myCheckboxTest" ng-submit="vm.checkItOut(decision)">_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="option" ng-model="decision.myWay"_x000D_
ng-value="false" ng-checked="!decision.myWay"> Should I stay?_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="option" ng-value="true"_x000D_
ng-model="decision.myWay" > Should I go?_x000D_
</label>_x000D_
_x000D_
</form>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
I hope I could help ;)
Those are users. Check your /etc/passwd
.
cd ~username
takes you to that user's home directory.
Installing opencv is not that direct. You need to pre-install some packages first.
I would not recommend the unofficial package opencv-python. Does not work properly in macos and ubuntu (see this post). No idea about windows.
There are many webs explaining how to install opencv and all required packages. For example this one.
The problem of trying to install opencv several times is that you need to uninstall completely before attempting again, or you might end having many errors.
The way to solve your problem is to use a Win32 API called WNetUseConnection.
Use this function to connect to a UNC path with authentication, NOT to map a drive.
This will allow you to connect to a remote machine, even if it is not on the same domain, and even if it has a different username and password.
Once you have used WNetUseConnection you will be able to access the file via a UNC path as if you were on the same domain. The best way is probably through the administrative built in shares.
Example: \\computername\c$\program files\Folder\file.txt
Here is some sample C# code that uses WNetUseConnection.
Note, for the NetResource, you should pass null for the lpLocalName and lpProvider. The dwType should be RESOURCETYPE_DISK. The lpRemoteName should be \\ComputerName.
using System;
using System.Runtime.InteropServices ;
using System.Threading;
namespace ExtremeMirror
{
public class PinvokeWindowsNetworking
{
#region Consts
const int RESOURCE_CONNECTED = 0x00000001;
const int RESOURCE_GLOBALNET = 0x00000002;
const int RESOURCE_REMEMBERED = 0x00000003;
const int RESOURCETYPE_ANY = 0x00000000;
const int RESOURCETYPE_DISK = 0x00000001;
const int RESOURCETYPE_PRINT = 0x00000002;
const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;
const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002;
const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003;
const int RESOURCEDISPLAYTYPE_FILE = 0x00000004;
const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005;
const int RESOURCEUSAGE_CONNECTABLE = 0x00000001;
const int RESOURCEUSAGE_CONTAINER = 0x00000002;
const int CONNECT_INTERACTIVE = 0x00000008;
const int CONNECT_PROMPT = 0x00000010;
const int CONNECT_REDIRECT = 0x00000080;
const int CONNECT_UPDATE_PROFILE = 0x00000001;
const int CONNECT_COMMANDLINE = 0x00000800;
const int CONNECT_CMD_SAVECRED = 0x00001000;
const int CONNECT_LOCALDRIVE = 0x00000100;
#endregion
#region Errors
const int NO_ERROR = 0;
const int ERROR_ACCESS_DENIED = 5;
const int ERROR_ALREADY_ASSIGNED = 85;
const int ERROR_BAD_DEVICE = 1200;
const int ERROR_BAD_NET_NAME = 67;
const int ERROR_BAD_PROVIDER = 1204;
const int ERROR_CANCELLED = 1223;
const int ERROR_EXTENDED_ERROR = 1208;
const int ERROR_INVALID_ADDRESS = 487;
const int ERROR_INVALID_PARAMETER = 87;
const int ERROR_INVALID_PASSWORD = 1216;
const int ERROR_MORE_DATA = 234;
const int ERROR_NO_MORE_ITEMS = 259;
const int ERROR_NO_NET_OR_BAD_PATH = 1203;
const int ERROR_NO_NETWORK = 1222;
const int ERROR_BAD_PROFILE = 1206;
const int ERROR_CANNOT_OPEN_PROFILE = 1205;
const int ERROR_DEVICE_IN_USE = 2404;
const int ERROR_NOT_CONNECTED = 2250;
const int ERROR_OPEN_FILES = 2401;
private struct ErrorClass
{
public int num;
public string message;
public ErrorClass(int num, string message)
{
this.num = num;
this.message = message;
}
}
// Created with excel formula:
// ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), "
private static ErrorClass[] ERROR_LIST = new ErrorClass[] {
new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"),
new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"),
new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"),
new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"),
new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"),
new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"),
new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"),
new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"),
new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"),
new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"),
new ErrorClass(ERROR_MORE_DATA, "Error: More Data"),
new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"),
new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"),
new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"),
new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"),
new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"),
new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"),
new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"),
new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"),
new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"),
};
private static string getErrorForNumber(int errNum)
{
foreach (ErrorClass er in ERROR_LIST)
{
if (er.num == errNum) return er.message;
}
return "Error: Unknown, " + errNum;
}
#endregion
[DllImport("Mpr.dll")] private static extern int WNetUseConnection(
IntPtr hwndOwner,
NETRESOURCE lpNetResource,
string lpPassword,
string lpUserID,
int dwFlags,
string lpAccessName,
string lpBufferSize,
string lpResult
);
[DllImport("Mpr.dll")] private static extern int WNetCancelConnection2(
string lpName,
int dwFlags,
bool fForce
);
[StructLayout(LayoutKind.Sequential)] private class NETRESOURCE
{
public int dwScope = 0;
public int dwType = 0;
public int dwDisplayType = 0;
public int dwUsage = 0;
public string lpLocalName = "";
public string lpRemoteName = "";
public string lpComment = "";
public string lpProvider = "";
}
public static string connectToRemote(string remoteUNC, string username, string password)
{
return connectToRemote(remoteUNC, username, password, false);
}
public static string connectToRemote(string remoteUNC, string username, string password, bool promptUser)
{
NETRESOURCE nr = new NETRESOURCE();
nr.dwType = RESOURCETYPE_DISK;
nr.lpRemoteName = remoteUNC;
// nr.lpLocalName = "F:";
int ret;
if (promptUser)
ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
else
ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);
if (ret == NO_ERROR) return null;
return getErrorForNumber(ret);
}
public static string disconnectRemote(string remoteUNC)
{
int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false);
if (ret == NO_ERROR) return null;
return getErrorForNumber(ret);
}
}
}
or this? By using row class
<div class="row">
<div class=" col-lg-2 col-md-2 col-sm-2 col-xs-2">
<h4>Panel header</h4>
</div>
<div class=" col-lg-10 col-md-10 col-sm-10 col-xs-10 ">
<div class="btn-group pull-right">
<a href="#" class="btn btn-default btn-sm">## Lock</a>
<a href="#" class="btn btn-default btn-sm">## Delete</a>
<a href="#" class="btn btn-default btn-sm">## Move</a>
</div>
</div>
</div>
</div>
The activity is declared NOT be recreated by rotation or keyboard slide.
Just got the same problem. Fix for API level 13 or higer.
From Android docs:
Note: If your application targets API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), then you should also declare the "screenSize" configuration, because it also changes when a device switches between portrait and landscape orientations.
So i've changed my manifest to this:
<activity
android:name="MyActivity"
android:configChanges="orientation|screenSize"
android:label="MyActivityName" >
</activity>
And now it works fine. Activity is not recreating when i rotate the phone, progress dialog and view stay the same. No error for me.
According to the manual this should work:
Custom key/value method:
You can include an operator in the first parameter in order to control the comparison:
$this->db->where('name !=', $name);
$this->db->where('id <', $id);
Produces: WHERE name != 'Joe' AND id < 45
Search for $this->db->where();
and look at item #2.
This is called an initialization list. It is for passing arguments to the constructor of a parent class. Here is a good link explaining it: Initialization Lists in C++
I use this:
if ($('.div1').size() || $('.div2').size()) {
console.log('ok');
}
I believe you are using the
echo Text >> Example.txt
function?
If so the answer would be simply adding a "." (Dot) directly after the echo with nothing else there.
Example:
echo Blah
echo Blah 2
echo. #New line is added
echo Next Blah
Put parentheses around the "OR"s:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND
(
ads.county_id = 2
OR ads.county_id = 5
OR ads.county_id = 7
OR ads.county_id = 9
)
Or even better, use IN:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2, 5, 7, 9)
A short answer is NO...
JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
Look at the reason why:
When exchanging data between a browser and a server, the data can only be text.
JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.
We can also convert any JSON received from the server into JavaScript objects.
This way we can work with the data as JavaScript objects, with no complicated parsing and translations.
But wait...
There is still ways to store your function, it's widely not recommended to that, but still possible:
We said, you can save a string
... how about converting your function to a string then?
const data = {func: '()=>"a FUNC"'};
Then you can stringify data using JSON.stringify(data)
and then using JSON.parse
to parse it (if this step needed)...
And eval to execute a string function (before doing that, just let you know using eval widely not recommended):
eval(data.func)(); //return "a FUNC"
No need to add any extra base64 library. Simple 5 line solution -
var img = new Image();
img.src = path.resolve('sample.jpg');
var doc = new jsPDF('p', 'mm', 'a3'); // optional parameters
doc.addImage(img, 'JPEG', 1, 2);
doc.save("new.pdf");
You can achieve this with: EventTarget.dispatchEvent(event)
and by passing in a new KeyboardEvent as the event.
For example: element.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}))
Working example:
// get the element in question_x000D_
const input = document.getElementsByTagName("input")[0];_x000D_
_x000D_
// focus on the input element_x000D_
input.focus();_x000D_
_x000D_
// add event listeners to the input element_x000D_
input.addEventListener('keypress', (event) => {_x000D_
console.log("You have pressed key: ", event.key);_x000D_
});_x000D_
_x000D_
input.addEventListener('keydown', (event) => {_x000D_
console.log(`key: ${event.key} has been pressed down`);_x000D_
});_x000D_
_x000D_
input.addEventListener('keyup', (event) => {_x000D_
console.log(`key: ${event.key} has been released`);_x000D_
});_x000D_
_x000D_
// dispatch keyboard events_x000D_
input.dispatchEvent(new KeyboardEvent('keypress', {'key':'h'}));_x000D_
input.dispatchEvent(new KeyboardEvent('keydown', {'key':'e'}));_x000D_
input.dispatchEvent(new KeyboardEvent('keyup', {'key':'y'}));
_x000D_
<input type="text" placeholder="foo" />
_x000D_
nop... just open the four dateis: content.xml; server.xml; tomcat-users.xml and web.xml in the tap servers. There are some text. Change the number of port 8080 to 8081
Python, at startup, loads a bunch of values into sys.path
(which is "implemented" via a list of strings), including:
$PYTHONPATH
rcfiles
)$PYTHONPATH
is only one part of the eventual value of sys.path
.
If you're after the value of sys.path
, the best way would be to ask Python (thanks @Codemonkey):
python -c "import sys; print sys.path"
Simply you can find index name and column names of a particular table using below command
SP_HELPINDEX 'tablename'
It work's for me
All of the other answers are correct. However, if the thing you want to alloc using alloca()
is reasonably small, I think that it's a good technique that's faster and more convenient than using malloc()
or otherwise.
In other words, alloca( 0x00ffffff )
is dangerous and likely to cause overflow, exactly as much as char hugeArray[ 0x00ffffff ];
is. Be cautious and reasonable and you'll be fine.
Note: there is no guarantee this code will work in future versions of the .Net framework. Using private .Net framework internals as done here through reflection is probably not good overall. Use the interop solution mentioned at the bottom, as the Windows API is less likely to change.
If you are looking for a Folder picker that looks more like the Windows 7 dialog, with the ability to copy and paste from a textbox at the bottom and the navigation pane on the left with favorites and common locations, then you can get access to that in a very lightweight way.
The FolderBrowserDialog UI is very minimal:
But you can have this instead:
Here's a class that opens a Vista-style folder picker using the .Net private IFileDialog
interface, without directly using interop in the code (.Net takes care of that for you). It falls back to the pre-Vista dialog if not in a high enough Windows version. Should work in Windows 7, 8, 9, 10 and higher (theoretically).
using System;
using System.Reflection;
using System.Windows.Forms;
namespace MyCoolCompany.Shuriken {
/// <summary>
/// Present the Windows Vista-style open file dialog to select a folder. Fall back for older Windows Versions
/// </summary>
public class FolderSelectDialog {
private string _initialDirectory;
private string _title;
private string _fileName = "";
public string InitialDirectory {
get { return string.IsNullOrEmpty(_initialDirectory) ? Environment.CurrentDirectory : _initialDirectory; }
set { _initialDirectory = value; }
}
public string Title {
get { return _title ?? "Select a folder"; }
set { _title = value; }
}
public string FileName { get { return _fileName; } }
public bool Show() { return Show(IntPtr.Zero); }
/// <param name="hWndOwner">Handle of the control or window to be the parent of the file dialog</param>
/// <returns>true if the user clicks OK</returns>
public bool Show(IntPtr hWndOwner) {
var result = Environment.OSVersion.Version.Major >= 6
? VistaDialog.Show(hWndOwner, InitialDirectory, Title)
: ShowXpDialog(hWndOwner, InitialDirectory, Title);
_fileName = result.FileName;
return result.Result;
}
private struct ShowDialogResult {
public bool Result { get; set; }
public string FileName { get; set; }
}
private static ShowDialogResult ShowXpDialog(IntPtr ownerHandle, string initialDirectory, string title) {
var folderBrowserDialog = new FolderBrowserDialog {
Description = title,
SelectedPath = initialDirectory,
ShowNewFolderButton = false
};
var dialogResult = new ShowDialogResult();
if (folderBrowserDialog.ShowDialog(new WindowWrapper(ownerHandle)) == DialogResult.OK) {
dialogResult.Result = true;
dialogResult.FileName = folderBrowserDialog.SelectedPath;
}
return dialogResult;
}
private static class VistaDialog {
private const string c_foldersFilter = "Folders|\n";
private const BindingFlags c_flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private readonly static Assembly s_windowsFormsAssembly = typeof(FileDialog).Assembly;
private readonly static Type s_iFileDialogType = s_windowsFormsAssembly.GetType("System.Windows.Forms.FileDialogNative+IFileDialog");
private readonly static MethodInfo s_createVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("CreateVistaDialog", c_flags);
private readonly static MethodInfo s_onBeforeVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("OnBeforeVistaDialog", c_flags);
private readonly static MethodInfo s_getOptionsMethodInfo = typeof(FileDialog).GetMethod("GetOptions", c_flags);
private readonly static MethodInfo s_setOptionsMethodInfo = s_iFileDialogType.GetMethod("SetOptions", c_flags);
private readonly static uint s_fosPickFoldersBitFlag = (uint) s_windowsFormsAssembly
.GetType("System.Windows.Forms.FileDialogNative+FOS")
.GetField("FOS_PICKFOLDERS")
.GetValue(null);
private readonly static ConstructorInfo s_vistaDialogEventsConstructorInfo = s_windowsFormsAssembly
.GetType("System.Windows.Forms.FileDialog+VistaDialogEvents")
.GetConstructor(c_flags, null, new[] { typeof(FileDialog) }, null);
private readonly static MethodInfo s_adviseMethodInfo = s_iFileDialogType.GetMethod("Advise");
private readonly static MethodInfo s_unAdviseMethodInfo = s_iFileDialogType.GetMethod("Unadvise");
private readonly static MethodInfo s_showMethodInfo = s_iFileDialogType.GetMethod("Show");
public static ShowDialogResult Show(IntPtr ownerHandle, string initialDirectory, string title) {
var openFileDialog = new OpenFileDialog {
AddExtension = false,
CheckFileExists = false,
DereferenceLinks = true,
Filter = c_foldersFilter,
InitialDirectory = initialDirectory,
Multiselect = false,
Title = title
};
var iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { });
s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog });
s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint) s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag });
var adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U };
s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken);
try {
int retVal = (int) s_showMethodInfo.Invoke(iFileDialog, new object[] { ownerHandle });
return new ShowDialogResult {
Result = retVal == 0,
FileName = openFileDialog.FileName
};
}
finally {
s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] });
}
}
}
// Wrap an IWin32Window around an IntPtr
private class WindowWrapper : IWin32Window {
private readonly IntPtr _handle;
public WindowWrapper(IntPtr handle) { _handle = handle; }
public IntPtr Handle { get { return _handle; } }
}
}
}
I developed this as a cleaned up version of .NET Win 7-style folder select dialog by Bill Seddon of lyquidity.com (I have no affiliation). I wrote my own because his solution requires an additional Reflection class that isn't needed for this focused purpose, uses exception-based flow control, doesn't cache the results of its reflection calls. Note that the nested static VistaDialog
class is so that its static reflection variables don't try to get populated if the Show
method is never called.
It is used like so in a Windows Form:
var dialog = new FolderSelectDialog {
InitialDirectory = musicFolderTextBox.Text,
Title = "Select a folder to import music from"
};
if (dialog.Show(Handle)) {
musicFolderTextBox.Text = dialog.FileName;
}
You can of course play around with its options and what properties it exposes. For example, it allows multiselect in the Vista-style dialog.
Also, please note that Simon Mourier gave an answer that shows how to do the exact same job using interop against the Windows API directly, though his version would have to be supplemented to use the older style dialog if in an older version of Windows. Unfortunately, I hadn't found his post yet when I worked up my solution. Name your poison!
In the case of a non blocking socket that has no data available, recv will throw the socket.error exception and the value of the exception will have the errno of either EAGAIN or EWOULDBLOCK. Example:
import sys
import socket
import fcntl, os
import errno
from time import sleep
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK)
while True:
try:
msg = s.recv(4096)
except socket.error, e:
err = e.args[0]
if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
sleep(1)
print 'No data available'
continue
else:
# a "real" error occurred
print e
sys.exit(1)
else:
# got a message, do something :)
The situation is a little different in the case where you've enabled non-blocking behavior via a time out with socket.settimeout(n)
or socket.setblocking(False)
. In this case a socket.error is stil raised, but in the case of a time out, the accompanying value of the exception is always a string set to 'timed out'. So, to handle this case you can do:
import sys
import socket
from time import sleep
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
s.settimeout(2)
while True:
try:
msg = s.recv(4096)
except socket.timeout, e:
err = e.args[0]
# this next if/else is a bit redundant, but illustrates how the
# timeout exception is setup
if err == 'timed out':
sleep(1)
print 'recv timed out, retry later'
continue
else:
print e
sys.exit(1)
except socket.error, e:
# Something else happened, handle error, exit, etc.
print e
sys.exit(1)
else:
if len(msg) == 0:
print 'orderly shutdown on server end'
sys.exit(0)
else:
# got a message do something :)
As indicated in the comments, this is also a more portable solution since it doesn't depend on OS specific functionality to put the socket into non-blockng mode.
See recv(2) and python socket for more details.