You are close, but the parameter you pass to SecureStringToBSTR
must be a SecureString
. You appear to be passing the result of ConvertFrom-SecureString
, which is an encrypted standard string. So call ConvertTo-SecureString
on this before passing to SecureStringToBSTR
.
$SecurePassword = ConvertTo-SecureString $PlainPassword -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
You can't declare an extern
local method inside of a method, or any other method with an attribute. Move your DLL import into the class:
using System.Runtime.InteropServices;
public class WindowHandling
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
public void ActivateTargetApplication(string processName, List<string> barcodesList)
{
Process p = Process.Start("notepad++.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;
}
}
I got this error when calling this code: wks.Range[startCell, endCell]
where the startCell
Range and endCell
Range were pointing to different worksheet then the variable wks
.
This is probably not a solution to your problem, but a suggestion just in case (I know I ran into a similar problem before but not with a .NET application).
If you are on a 64-bit machine, there are 2 regsvr32.exe
files;
One is in \Windows\System32
and the other one is in \Windows\SysWOW64
.
You cannot register 64-bit COM-objects with the 32-bit version, but you can do it vice versa. I'd try registering your DLL with both regsvr32.exe
files explicitly (i.e. typing "C:\Windows\System32\regsvr32.exe /i mydll.dll
" and then "C:\Windows\SysWOW64\regsvr32.exe /i mydll.dll
") and seeing if that helps...
I was looking at this issue as well, and in my case the solution was too easy. I added a new empty project to the solution. The newly added project is automatically set as a console application. But since the project added was a 'empty' project, no Program.cs existed in that new project. (As expected)
All I needed to do was change the output type of the project properties to Class library
Microsoft API Code Pack. ShellObjectWatcher class.
Other way could be this one:
driver.FindElement(By.XPath(".//*[@id='examp']/form/select[1]/option[3]")).Click();
and you can change the index in option[x] changing x by the number of element that you want to select.
I don't know if it is the best way but I hope that help you.
For all of those, who still experiencing this problem, I just spent 2 days tracking down the bloody thing. I was getting the same error when there was no rows in dataset. Seems obvious, but error message is very obscure, hence 2 days.
Probably you are trying to access the excel with the index 0, please note that Excel rows/columns start from 1.
Add the following in the config file, and it will be caught in try catch block. Word of caution... try to avoid this situation, as this means some kind of violation is happening.
<configuration>
<runtime>
<legacyCorruptedStateExceptionsPolicy enabled="true" />
</runtime>
</configuration>
Hope this help
private bool isDate(Range cell)
{
if (cell.NumberFormat.ToString().Contains("/yy"))
{
return true;
}
return false;
}
isDate(worksheet.Cells[irow, icol])
Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.
If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll
(assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.
If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).
In the context of Ektron, this issue is resolved by installing the "IIS6 Metabase compatibility" feature in Windows:
Check 'Windows features' or 'Role Services' for IIS6 Metabase compatibility, add if missing:
The component makers say that this has been fixed in the latest version of their component which we are using in-house, but this has been given to the customer yet.
Ask the component maker how to test whether the problem that the customer is getting is the problem which they say they've fixed in their latest version, without/before deploying their latest version to the customer.
You need to add a TraceListener
to see them appear on the Console.
TextWriterTraceListener writer = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(writer);
They also appear in the Visual Studio Output window when in Debug mode.
One other cause of this error and that solve my problème is that your application doesn't have a write permission on some directory.
so to complete the answer of savindra : https://stackoverflow.com/a/7426516/6444829.
Here is how you Grant File Access to IIS_IUSERS
To provide access to an ASP.NET application, you must grant access to the IIs_IUSERS.
To grant read, write, and modify permissions to a specific File or Folder
In Windows Explorer, locate and select the required file.
Right click the file, and then click Properties.
In the Properties dialog box, click the Security tab.
On the Security tab, examine the list of users. (If your application is running as a Network Service, add the network service account in the list and grant it the permission.
In the Properties dialog box, click IIs_IUSERS, and in the Permissions for NETWORK SERVICE section, select the Read, Write, and Modify permissions.
Click Apply, and then click OK.
this worked for me in my IIS of windows server 2016 and local IIS windows 10.
What @Bogdan Maxim said. Or change to use InProc if you're not using an external sesssion state server.
<sessionState mode="InProc" timeout="20" cookieless="AutoDetect" />
Look here for more info on the SessionState directive.
My answer is late and its only purpose is to support the solution proposed by Govert, Porkbutts, and Dave Cousineau with a complete example. Automating Excel or other COM objects from the COM-agnostic .NET world is a “tough nut,” as we say in German, and you can easily go nuts. I rely on the following steps:
For each interaction with Excel, get one and only one local instance ExcelApp
of the Application interface and create a scope within which ExcelApp
lives. This is necessary, because the CLR won’t free the resources of Excel before any reference to Excel goes out of scope. A new Excel process is started in the background.
Implement functions that do the tasks by using ExcelApp
to
generate via Collection properties new objects like Workbook(s),
Worksheet(s), and Cell(s). In these functions don’t care for the
voodoo one-dot-good, two-dot-bad rule, don’t try to get a reference
for each implicitly created object and don’t
Marshall.ReleaseComObject
anything. That is the job of the Garbage
Collection.
Within the scope of ExcelApp
, call these functions and pass the reference ExcelApp
.
While your Excel instance is loaded, don’t allow any user actions that would bypass the Quit
function that unloads this instance again.
When you are done with Excel, call the separate Quit
function within the scope made for Excel handling. This should be the last statement within this scope.
Before you run my app, open the task manager and watch in the Processes tab the entries in background processes. When you start the program, a new Excel process entry appears in the list and stays there until the thread wakes up again after 5 seconds. After that the Quit function will be called, stopping the Excel process that gracefully vanishes from the list of background processes.
using System;
using System.Threading;
using Excel = Microsoft.Office.Interop.Excel;
namespace GCTestOnOffice
{
class Program
{
//Don't: private static Excel.Application ExcelApp = new Excel.Application();
private static void DoSomething(Excel.Application ExcelApp)
{
Excel.Workbook Wb = ExcelApp.Workbooks.Open(@"D:\Aktuell\SampleWorkbook.xlsx");
Excel.Worksheet NewWs = Wb.Worksheets.Add();
for (int i = 1; i < 10; i++)
{
NewWs.Cells[i, 1] = i;
}
Wb.Save();
}
public static void Quit(Excel.Application ExcelApp)
{
if (ExcelApp != null)
{
ExcelApp.Quit(); //Don't forget!!!!!
ExcelApp = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
static void Main(string[] args)
{
{
Excel.Application ExcelApp = new Excel.Application();
Thread.Sleep(5000);
DoSomething(ExcelApp);
Quit(ExcelApp);
//ExcelApp goes out of scope, the CLR can and will(!) release Excel
}
Console.WriteLine("Input a digit: ");
int k = Console.Read();
}
}
}
If I changed the Main function to
static void Main(string[] args)
{
Excel.Application ExcelApp = new Excel.Application();
DoSomething(ExcelApp);
Console.WriteLine("Input a digit: ");
int k = Console.Read();
Quit(ExcelApp);
}
the user could instead of inputting a number, hit the Close button of the console and my Excel instance lived happily ever after. So, in cases where your Excel instance remains stubbornly loaded, your cleanup feature might not be wrong, but is bypassed by unforeseen user actions.
If the Program class would have a member for the Excel instance, the CLR would not unload the Excel instance before the app terminates. That's why I prefer local references that go out of scope when they are no longer needed.
Do you even need MSDTC? The escalation you're experiencing is often caused by creating multiple connections within a single TransactionScope.
If you do need it then you need to enable it as outlined in the error message. On XP:
select *
from tempdb.INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME=OBJECT_NAME(OBJECT_ID('#table'))
Constructors don't return a type , just remove the return type which is void in your case. It would run fine then.
See my answer to the question Importing modules from parent folder for related information, including why my answer doesn't use the unreliable __file__
variable. This simple solution should be cross-compatible with different operating systems as the modules os
and inspect
come as part of Python.
First, you need to import parts of the inspect and os modules.
from inspect import getsourcefile
from os.path import abspath
Next, use the following line anywhere else it's needed in your Python code:
abspath(getsourcefile(lambda:0))
From the built-in module os
(description below), the abspath
tool is imported.
OS routines for Mac, NT, or Posix depending on what system we're on.
Then getsourcefile
(description below) is imported from the built-in module inspect
.
Get useful information from live Python objects.
abspath(path)
returns the absolute/full version of a file pathgetsourcefile(lambda:0)
somehow gets the internal source file of the lambda function object, so returns '<pyshell#nn>'
in the Python shell or returns the file path of the Python code currently being executed.Using abspath
on the result of getsourcefile(lambda:0)
should make sure that the file path generated is the full file path of the Python file.
This explained solution was originally based on code from the answer at How do I get the path of the current executed file in Python?.
From
https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation
When you create a new ASP.NET Core 2.0 application, this hook is included by default. In previous versions of EF Core and ASP.NET Core, the tools try to invoke Startup.ConfigureServices directly in order to obtain the application's service provider, but this pattern no longer works correctly in ASP.NET Core 2.0 applications. If you are upgrading an ASP.NET Core 1.x application to 2.0, you can modify your Program class to follow the new pattern.
Add Factory in .Net Core 2.x
public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
{
public BloggingContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");
return new BloggingContext(optionsBuilder.Options);
}
}
Ok so your code actually works but what you need to do is replace a and b in your click function with the jquery notation you used before the click. This will ensure you have the correct and most up to date values. so changing your click function to this should work:
$("submit").on("click", function(){
var sum = $("#a").val().match(/\d+/) + $("#b").val().match(/\d+/);
alert(sum);
})
or inlined to:
$("submit").on("click", function(){
alert($("#a").val().match(/\d+/) + $("#b").val().match(/\d+/));
})
If you run Tomcat on Windows, you can use the neat "Tomcat Monitor" application that ships with Tomcat.
Go to the Java tab. At the bottom, below the "Java Options" textarea, you will find 3 input fields:
Intent serviceIntent = new Intent(this,YourActivity.class);
startService(serviceIntent);
add service in manifist
<service android:enabled="true" android:name="YourActivity.class" />
for running service on oreo and greater devices use for ground service and show notification to user
or use geofencing service for location update in background reference http://stackoverflow.com/questions/tagged/google-play-services
you can find Java Communications API 2.0 in below link
I am not sure about this tutorial but I had the same problem when I forgot to include the file into grunt/gulp minimization process.
grunt.initConfig({
uglify: {
my_target: {
files: {
'dest/output.min.js': ['src/input1.js', 'src/missing_controller.js']
}
}
}
});
Hope that helps.
1-Install AjaxControl Toolkit easily by Nugget
PM> Install-Package AjaxControlToolkit
2-then in markup
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:TextBox ID="txtMovie" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" TargetControlID="txtMovie"
runat="server" />
3- in code-behind : to get the suggestions
[System.Web.Services.WebMethodAttribute(),System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey) {
// Create array of movies
string[] movies = {"Star Wars", "Star Trek", "Superman", "Memento", "Shrek", "Shrek II"};
// Return matching movies
return (from m in movies where m.StartsWith(prefixText,StringComparison.CurrentCultureIgnoreCase) select m).Take(count).ToArray();
}
source: http://www.asp.net/ajaxlibrary/act_autocomplete_simple.ashx
It's taking the ID , dividing it by 2 and checking if the remainder is not zero; meaning, it's an odd ID.
Since mysql_* are deprecated, so here is the solution using mysqli.
$mysqli = new mysqli('host', 'username', 'password', 'database');
if($mysqli->connect_errno>0)
{
die("Connection to MySQL-server failed!");
}
$resultArr = array();//to store results
//to execute query
$executingFetchQuery = $mysqli->query("SELECT `name` FROM customers WHERE 1");
if($executingFetchQuery)
{
while($arr = $executingFetchQuery->fetch_assoc())
{
$resultArr[] = $arr['name'];//storing values into an array
}
}
print_r($resultArr);//print the rows returned by query, containing specified columns
There is another way to do this using PDO
$db = new PDO('mysql:host=host_name;dbname=db_name', 'username', 'password'); //to establish a connection
//to fetch records
$fetchD = $db->prepare("SELECT `name` FROM customers WHERE 1");
$fetchD->execute();//executing the query
$resultArr = array();//to store results
while($row = $fetchD->fetch())
{
$resultArr[] = $row['name'];
}
print_r($resultArr);
Just to give some examples. Let's say you modify the password for an user called 'alex'. You can modify this password in several ways. For instance:
mysql> update* user set password=PASSWORD('test!23') where user='alex';
mysql> flush privileges;
Here you used UPDATE. If you use INSERT, UPDATE or DELETE on grant tables directly you need use FLUSH PRIVILEGES in order to reload the grant tables.
Or you can modify the password like this:
mysql> set password for 'alex'@'localhost'= password('test!24');
Here it's not necesary to use "FLUSH PRIVILEGES;" If you modify the grant tables indirectly using account-management statements such as GRANT, REVOKE, SET PASSWORD, or RENAME USER, the server notices these changes and loads the grant tables into memory again immediately.
From your comment to gnibbler answer, i'd say you want a list of pairs of key-value sorted by value:
sorted(data.items(), key=lambda x:x[1])
For Swift3/Swift4 Developers:
let radius = yourImageView.frame.width / 2
yourImageView.layer.cornerRadius = radius
yourImageView.layer.masksToBounds = true
You would need to decompile the apk as Davis suggested, can use tools such as apkTool , then if you need to change the source code you would need other tools to do that.
You would then need to put the apk back together and sign it, if you don't have the original key used to sign the apk this means the new apk will have a different signature.
If the developer employed any obfuscation or other techniques to protect the app then it gets more complicated.
In short its a pretty complex and technical procedure, so if the developer is really just out of reach, its better to wait until he is in reach. And ask for the source code next time.
You can get access token using FB.getAuthResponse()['accessToken']
:
FB.login(function(response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: ''});
Edit:
Updated to use Oauth 2.0, required since December 2011. Now uses FB.getAuthResponse();
If you are using a browser that does not have a console, (I'm talking to you, Internet Explorer) be sure to comment out the console.log
lines or use a log-failsafe script such as:
if (typeof(console) == "undefined") { console = {}; }
if (typeof(console.log) == "undefined") { console.log = function() { return 0; } }
You do not have Gemfile
in a directory where you run that command.
Gemfile
is a file containing your gem
settings for a current program.
just bash
mystring=$(printf "%s|" *)
echo ${mystring%|}
Following @user2019515 answer, I needed to handle exclusions to my archive. here is the resulting function with an example.
Zip Function :
function Zip($source, $destination, $include_dir = false, $exclusions = false){
// Remove existing archive
if (file_exists($destination)) {
unlink ($destination);
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true){
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
if ($include_dir) {
$arr = explode("/",$source);
$maindir = $arr[count($arr)- 1];
$source = "";
for ($i=0; $i < count($arr) - 1; $i++) {
$source .= '/' . $arr[$i];
}
$source = substr($source, 1);
$zip->addEmptyDir($maindir);
}
foreach ($files as $file){
// Ignore "." and ".." folders
$file = str_replace('\\', '/', $file);
if(in_array(substr($file, strrpos($file, '/')+1), array('.', '..'))){
continue;
}
// Add Exclusion
if(($exclusions)&&(is_array($exclusions))){
if(in_array(str_replace($source.'/', '', $file), $exclusions)){
continue;
}
}
$file = realpath($file);
if (is_dir($file) === true){
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
} elseif (is_file($file) === true){
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
} elseif (is_file($source) === true){
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
How to use it :
function backup(){
$backup = 'tmp/backup-'.$this->site['version'].'.zip';
$exclusions = [];
// Excluding an entire directory
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('tmp/'), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file){
array_push($exclusions,$file);
}
// Excluding a file
array_push($exclusions,'config/config.php');
// Excluding the backup file
array_push($exclusions,$backup);
$this->Zip('.',$backup, false, $exclusions);
}
OK, I have found the problem.
I use some reporting plugins. In the documentation of the failsafe-maven-plugin
I found, that the <encoding>
configuration - of course - uses ${project.reporting.outputEncoding}
by default.
So I added the property as a child element of the project
element and everything is fine now:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
See also http://maven.apache.org/general.html#encoding-warning
I think this answer in "Vim clear last search highlighting" is better:
:let @/ = ""
Here is full code. The result is exactly what you want.
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
if __name__ == '__main__':
animal = Animal()
temp = vars(animal)
for item in temp:
print item , ' : ' , temp[item]
#print item , ' : ', temp[item] ,
For me it worked doing this:
Uninstall the previous version: go to C:\users\username\anaconda3 and run the anaconda-uninstall.exe
Install again anaconda
then run the following commands on the anaconda pompt:
conda create -n my_env python=2.7
conda activate my_env
start the gui app
anaconda-navigator
There are four main alternatives. Both have their quirks, but Method 4 has many advantages from my view.
./script
is a shell script starting by #!/usr/bin/php
Method 1: $argv
./script hello wo8844rld
// $argv[0] = "script", $argv[1] = "hello", $argv[2] = "wo8844rld"
?? Using $argv, the parameter order is critical.
Method 2: getopt()
./script -p7 -e3
// getopt("p::")["p"] = "7", getopt("e::")["e"] = "3"
It's hard to use in conjunction of $argv
, because:
?? The parsing of options will end at the first non-option found, anything that follows is discarded.
?? Only 26 parameters as the alphabet.
Method 3: Bash Global variable
P9="xptdr" ./script
// getenv("P9") = "xptdr"
// $_SERVER["P9"] = "xptdr"
Those variables can be used by other programs running in the same shell.
They are blown when the shell is closed, but not when the PHP program is terminated. We can set them permanent in file ~/.bashrc!
Method 4: STDIN pipe and stream_get_contents()
Some piping examples:
Feed a string:
./script <<< "hello wo8844rld"
// stream_get_contents(STDIN) = "hello wo8844rld"
Feed a string using bash echo:
echo "hello wo8844rld" | ./script
// explode(" ",stream_get_contents(STDIN)) ...
Feed a file content:
./script < ~/folder/Special_params.txt
// explode("\n",stream_get_contents(STDIN)) ...
Feed an array of values:
./script <<< '["array entry","lol"]'
// var_dump( json_decode(trim(stream_get_contents(STDIN))) );
Feed JSON content from a file:
echo params.json | ./script
// json_decode(stream_get_contents(STDIN)) ...
It might work similarly to fread() or fgets(), by reading the STDIN.
Note: The last line is mandatory.
If we didn't specify Access-Control-Expose-Headers, we will not get File Name in UI.
FileInfo file = new FileInfo(FILEPATH);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = file.Name
};
response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
nslookup google.com
is the easiest way. Works on Linux and Windows.
If your issue is that your DNS server is not returning a response for google.com, use a different DNS server, such as a public one. For instance, you could do:
nslookup
>server 8.8.8.8
>google.com
For a more thorough solution to getting around annoying Internet filters, look into using Tor.
There are plenty of examples of using JQuery to retrieve the mouse coordinates, but none fixed my issue.
The Body of my webpage is 1000 pixels wide, and I centre it in the middle of the user's browser window.
body {
position:absolute;
width:1000px;
left: 50%;
margin-left:-500px;
}
Now, in my JavaScript code, when the user right-clicked on my page, I wanted a div to appear at the mouse position.
Problem is, just using e.pageX value wasn't quite right. It'd work fine if I resized my browser window to be about 1000 pixels wide. Then, the pop div would appear at the correct position.
But if increased the size of my browser window to, say, 1200 pixels wide, then the div would appear about 100 pixels to the right of where the user had clicked.
The solution is to combine e.pageX with the bounding rectangle of the body element. When the user changes the size of their browser window, the "left" value of body element changes, and we need to take this into account:
// Temporary variables to hold the mouse x and y position
var tempX = 0;
var tempY = 0;
jQuery(document).ready(function () {
$(document).mousemove(function (e) {
var bodyOffsets = document.body.getBoundingClientRect();
tempX = e.pageX - bodyOffsets.left;
tempY = e.pageY;
});
})
Phew. That took me a while to fix ! I hope this is useful to other developers !
For any React Router v4 users arriving here following a search, optional parameters in a <Route>
are denoted with a ?
suffix.
Here's the relevant documentation:
https://reacttraining.com/react-router/web/api/Route/path-string
path: string
Any valid URL path that path-to-regexp understands.
<Route path="/users/:id" component={User}/>
https://www.npmjs.com/package/path-to-regexp#optional
Optional
<Route path="/section/:page?" component={Section} />
In my case, it was the problem when I setup my time manually two month earlier on my iPhone. But when I changed to set time automatically, it worked fine.
Setting
-> General
-> Date & Time
-> set time automatically
If it does not work set time automatically of both mac & iPhone, will work fine.
Try this
You_command 1>output.log 2>&1
Your usage of &>x.file does work in bash4. sorry for that : (
0, 1, 2...9 are file descriptors in bash.
0 stands for stdin
, 1 stands for stdout
, 2 stands for stderror
. 3~9 is spare for any other temporary usage.
Any file descriptor can be redirected to other file descriptor or file by using operator >
or >>
(append).
Usage: <file_descriptor> > <filename | &file_descriptor>
Please reference to http://www.tldp.org/LDP/abs/html/io-redirection.html
To get a better idea, all you need are the following files
You could put everything else in the .gitignore file. All your app changes lies mostly in these files and folders. The rest you see in a basic project are gradle build files or Android Studio configuration files.
If you are using Android Studio, you can use "Import project" to successfully build the project. Alternatively you can build using command line, follow Building Android Projects with Gradle.
You need to use control characters as backslash (\b) and carriage return (\r). It come disabled by default, but the Console view can interpret these controls.
Windows>Preferences and Run/Debug > Console and select Interpret ASCII control characteres to enabled it
After these configurations, you can manage your console with control characters like:
\t - tab.
\b - backspace (a step backward in the text or deletion of a single character).
\n - new line.
\r - carriage return. ()
\f - form feed.
More information at: https://www.eclipse.org/eclipse/news/4.14/platform.php
follow this thread for more information
CSS Attribute Selector: Apply class if custom attribute has value? Also, will it work in IE7+?
and learn css attribute selector
There's several things you can improve upon here. To start, there's no reason to use an <a>
(anchor) tag since you don't have a link.
Every element can be bound to click and hover events... divs, spans, labels, inputs, etc.
I can't really identify what it is you're trying to do, though. You're mixing the goal with your own implementation and, from what I've seen so far, you're not really sure how to do it. Could you better illustrate what it is you're trying to accomplish?
== EDIT ==
The requirements are still very vague. I've implemented a very quick version of what I'm imagining you're saying ... or something close that illustrates how you might be able to do it. Left me know if I'm on the right track.
please try to make it as a character
string str = "Tigger";
//then str[0] will return 'T' not "T"
i ended up with double check of status. php 5.4+
if(session_status() !== PHP_SESSION_ACTIVE){session_start();};
if(session_status() !== PHP_SESSION_ACTIVE){die('session start failed');};
From a sqlite prompt:
sqlite> .read db.sql
Or:
cat db.sql | sqlite3 database.db
Also, your SQL is invalid - you need ;
on the end of your statements:
create table server(name varchar(50),ipaddress varchar(15),id init);
create table client(name varchar(50),ipaddress varchar(15),id init);
add label
to subview
of custom view
, no need of self.view.addSubview(view)
, because viewForHeaderInSection
return the UIView
view.addSubview(label)
I´ve been working in Kotlin (recommend to everyone), so the syntax might be a bit off. What I do is to simply to call:
v.animate().alpha(0f).duration = 200
I think that, in Java, it would be the following.:
v.animate().alpha(0f).setDuration(200);
Try:
private void hide(View v, int duration) {
v.animate().alpha(0f).setDuration(duration);
}
private void show(View v, int duration) {
v.animate().alpha(1f).setDuration(duration);
}
Your null pointer exception seems to be on this line:
String url = intent.getExtras().getString("userurl");
because intent.getExtras()
returns null when the intent doesn't have any extras.
You have to realize that this piece of code:
Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);
doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass
and if that doesn't exist, your app crashes.
Also, there is no such thing as "android.intent.action.start"
so the manifest should look more like:
<activity android:name=".start" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name= ".Main">
</activity>
I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.
Try this:
String sMillis = "10997195233";
double dMillis = 0;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
int millis = 0;
String sTime;
try {
dMillis = Double.parseDouble(sMillis);
} catch (Exception e) {
System.out.println(e.getMessage());
}
seconds = (int)(dMillis / 1000) % 60;
millis = (int)(dMillis % 1000);
if (seconds > 0) {
minutes = (int)(dMillis / 1000 / 60) % 60;
if (minutes > 0) {
hours = (int)(dMillis / 1000 / 60 / 60) % 24;
if (hours > 0) {
days = (int)(dMillis / 1000 / 60 / 60 / 24);
if (days > 0) {
sTime = days + " days " + hours + " hours " + minutes + " min " + seconds + " sec " + millis + " millisec";
} else {
sTime = hours + " hours " + minutes + " min " + seconds + " sec " + millis + " millisec";
}
} else {
sTime = minutes + " min " + seconds + " sec " + millis + " millisec";
}
} else {
sTime = seconds + " sec " + millis + " millisec";
}
} else {
sTime = dMillis + " millisec";
}
System.out.println("time: " + sTime);
Google posted a solution for this kind of problem here.
The steps:
3333
on the left part, and type localhost:5000
, and click add rule.While it does not answer the OP's question precisely, depending on what you're doing it might be a good solution. Below is going to solve my problem.
Let's say that you have to do a lot of individual manipulation of various characters in a string. Instead of using a string the whole time use a char[]
array while you're doing the manipulation. Because you can do this:
char[] array = "valta is the best place in the World".ToCharArray();
Then manipulate to your hearts content as much as you need...
array[0] = "M";
Then convert it to a string once you're done and need to use it as a string:
string str = new string(array);
So I see here tons of answers that are frankly overcomplicated, and that's an understatement.
The answer is pretty simple: :: it's called a Method References https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
So I won't copy-paste, on the link, you can find all the information if you scroll down to the table.
Now, let's take a short look at what is a Method References:
A::b somewhat substitutes the following inline lambda expression: (params ...) -> A.b(params ...)
To correlate this with your questions, it's necessary to understand a java lambda expression. Which is not hard.
An inline lambda expression is similar to a defined functional interface (which is an interface that has no more and no less than 1 method). Let's take a short look what I mean:
InterfaceX f = (x) -> x*x;
InterfaceX must be a functional interface. Any functional interface, the only thing what's important about InterfaceX for that compiler is that you define the format:
InterfaceX can be any of this:
interface InterfaceX
{
public Integer callMe(Integer x);
}
or this
interface InterfaceX
{
public Double callMe(Integer x);
}
or more generic:
interface InterfaceX<T,U>
{
public T callMe(U x);
}
Let's take the first presented case and the inline lambda expression that we defined earlier.
Before Java 8, you could've defined it similarly this way:
InterfaceX o = new InterfaceX(){
public int callMe (int x)
{
return x*x;
} };
Functionally, it's the same thing. The difference is more in how the compiler perceives this.
Now that we took a look at inline lambda expression, let's return to Method References (::). Let's say you have a class like this:
class Q {
public static int anyFunction(int x)
{
return x+5;
}
}
Since method anyFunctions has the same types as InterfaceX callMe, we can equivalate those two with a Method Reference.
We can write it like this:
InterfaceX o = Q::anyFunction;
and that is equivalent to this :
InterfaceX o = (x) -> Q.anyFunction(x);
A cool thing and advantage of Method References are that at first, until you assign them to variables, they are typeless. So you can pass them as parameters to any equivalent looking (has same defined types) functional interface. Which is exactly what happens in your case
Typically, permissions issues with a host volume mount are because the uid/gid inside the container does not have access to the file according to the uid/gid permissions of the file on the host. However, this specific case is different.
The dot at the end of the permission string, drwxr-xr-x.
, indicates SELinux is configured. When using a host mount with SELinux, you need to pass an extra option to the end of the volume definition:
- The
z
option indicates that the bind mount content is shared among multiple containers.- The
Z
option indicates that the bind mount content is private and unshared.
Your volume mount command would then look like:
sudo docker run -i -v /data1/Downloads:/Downloads:z ubuntu bash
See more about host mounts with SELinux at: https://docs.docker.com/storage/bind-mounts/#configure-the-selinux-label
For others that see this issue with containers running as a different user, you need to ensure the uid/gid of the user inside the container has permissions to the file on the host. On production servers, this is often done by controlling the uid/gid in the image build process to match a uid/gid on the host that has access to the files (or even better, do not use host mounts in production).
A named volume is often preferred to host mounts because it will initialize the volume directory from the image directory, including any file ownership and permissions. This happens when the volume is empty and the container is created with the named volume.
MacOS users now have OSXFS which handles uid/gid's automatically between the Mac host and containers. One place it doesn't help with are files from inside the embedded VM that get mounted into the container, like /var/lib/docker.sock.
For development environments where the host uid/gid may change per developer, my preferred solution is to start the container with an entrypoint running as root, fix the uid/gid of the user inside the container to match the host volume uid/gid, and then use gosu
to drop from root to the container user to run the application inside the container. The important script for this is fix-perms
in my base image scripts, which can be found at: https://github.com/sudo-bmitch/docker-base
The important bit from the fix-perms
script is:
# update the uid
if [ -n "$opt_u" ]; then
OLD_UID=$(getent passwd "${opt_u}" | cut -f3 -d:)
NEW_UID=$(stat -c "%u" "$1")
if [ "$OLD_UID" != "$NEW_UID" ]; then
echo "Changing UID of $opt_u from $OLD_UID to $NEW_UID"
usermod -u "$NEW_UID" -o "$opt_u"
if [ -n "$opt_r" ]; then
find / -xdev -user "$OLD_UID" -exec chown -h "$opt_u" {} \;
fi
fi
fi
That gets the uid of the user inside the container, and the uid of the file, and if they do not match, calls usermod
to adjust the uid. Lastly it does a recursive find to fix any files which have not changed uid's. I like this better than running a container with a -u $(id -u):$(id -g)
flag because the above entrypoint code doesn't require each developer to run a script to start the container, and any files outside of the volume that are owned by the user will have their permissions corrected.
You can also have docker initialize a host directory from an image by using a named volume that performs a bind mount. This directory must exist in advance, and you need to provide an absolute path to the host directory, unlike host volumes in a compose file which can be relative paths. The directory must also be empty for docker to initialize it. Three different options for defining a named volume to a bind mount look like:
# create the volume in advance
$ docker volume create --driver local \
--opt type=none \
--opt device=/home/user/test \
--opt o=bind \
test_vol
# create on the fly with --mount
$ docker run -it --rm \
--mount type=volume,dst=/container/path,volume-driver=local,volume-opt=type=none,volume-opt=o=bind,volume-opt=device=/home/user/test \
foo
# inside a docker-compose file
...
volumes:
bind-test:
driver: local
driver_opts:
type: none
o: bind
device: /home/user/test
...
Lastly, if you try using user namespaces, you'll find that host volumes have permission issues because uid/gid's of the containers are shifted. In that scenario, it's probably easiest to avoid host volumes and only use named volumes.
Use Sheets rather than Sheet and activate them sequentially:
Sub kl()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
Set ws = Sheets("Sheet1")
wb.Activate
ws.Select
End Sub
The iframe element.
<iframe src="name.html"></iframe>
But content that you way to have appear on multiple pages is better handled using templates.
Andrey's answer (the highest voted at the time of writing) is slightly incorrect. I would have added this as comment but I am not reputable enough.
In Andrey's answer:
char[] chars = {'c', 'h', 'a', 'r', 's'}
byte[] bytes = Charset.forName("UTF-8").encode(CharBuffer.wrap(chars)).array();
the call to array() may not return the desired value, for example:
char[] c = "aaaaaaaaaa".toCharArray();
System.out.println(Arrays.toString(Charset.forName("UTF-8").encode(CharBuffer.wrap(c)).array()));
output:
[97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0]
As can be seen a zero byte has been added. To avoid this use the following:
char[] c = "aaaaaaaaaa".toCharArray();
ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(c));
byte[] b = new byte[bb.remaining()];
bb.get(b);
System.out.println(Arrays.toString(b));
output:
[97, 97, 97, 97, 97, 97, 97, 97, 97, 97]
As the answer also alluded to using passwords it might be worth blanking out the array that backs the ByteBuffer (accessed via the array() function):
ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(c));
byte[] b = new byte[bb.remaining()];
bb.get(b);
blankOutByteArray(bb.array());
System.out.println(Arrays.toString(b));
This method helped me when trying to retrieve data from Text File and store it in Array then Assign it to a string avariable.
string[] lines = File.ReadAllLines(Environment.CurrentDirectory + "\\Notes.txt");
string marRes = string.Join(Environment.NewLine, lines.ToArray());
Hopefully may help Someone!!!!
open notepad++, then drag and drop the folder you want to open as tree view.
OR
File ->open folder as workspace , select the file you want.
filtered_list = [list_a[i] for i in range(len(list_a)) if filter[i]]
Try using putting the ASCII character for the dash in between the digit separations.
from this: -
to this: –
ex: change 555-555-5555
=> 555–555–5555
The command you are looking for is git clean
Here's a short complete html example. See demo http://jsfiddle.net/CU585/
<!DOCTYPE html><html><head><title>resizable columns</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
<style>
th {border: 1px solid black;}
table{border-collapse: collapse;}
.ui-icon, .ui-widget-content .ui-icon {background-image: none;}
</style>
<body>
<table>
<tr><th>head 1</th><th>head 2</th></tr><tr><td>a1</td><td>b1</td></tr></table><script>
$( "th" ).resizable();
</script></body></html>
If you are seraching for whole words you can do this that works case insensitive.
private boolean containsKeyword(String line, String[] keywords)
{
String[] inputWords = line.split(" ");
for (String inputWord : inputWords)
{
for (String keyword : keywords)
{
if (inputWord.equalsIgnoreCase(keyword))
{
return true;
}
}
}
return false;
}
A cute piece of numerical weirdness may be observed if one converts 9999999.4999999999 to a float
and back to a double
. The result is reported as 10000000, even though that value is obviously closer to 9999999, and even though 9999999.499999999 correctly rounds to 9999999.
Totally agree with @tir38 and @android_griezmann. This would be the version in kotlin:
interface servicesEndPoint {
@Multipart
@POST("user/updateprofile")
fun updateProfile(@Part("user_id") id:RequestBody, @Part("full_name") other:fullName, @Part image: MultipartBody.Part, @Part("other") other:RequestBody): Single<UploadPhotoResponse>
companion object {
val API_BASE_URL = "YOUR_URL"
fun create(): servicesPhotoEndPoint {
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(API_BASE_URL)
.build()
return retrofit.create(servicesPhotoEndPoint::class.java)
}
}
}
// pass it like this
val file = File(RealPathUtils.getRealPathFromURI_API19(context, uri))
val requestFile: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
// MultipartBody.Part is used to send also the actual file name
val body: MultipartBody.Part = MultipartBody.Part.createFormData("image", file.name, requestFile)
// add another part within the multipart request
val fullName: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name")
servicesEndPoint.create().updateProfile(id, fullName, body, fullName)
To obtain the real path, use RealPathUtils. Check this class in the answers of @Harsh Bhavsar in this question: How to get the Full file path from URI.
To getRealPathFromURI_API19 you need permissions of READ_EXTERNAL_STORAGE
I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.
For example:
$("#id_form").on("submit", function(){
//Code: Action (like ajax...)
return false;
})
Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.
This might not be as fast as the izip_longest solution (I didn't actually test it), but it will work with python < 2.6 (izip_longest was added in 2.6):
from itertools import imap
def grouper(n, iterable):
"grouper(3, 'ABCDEFG') --> ('A,'B','C'), ('D','E','F'), ('G',None,None)"
args = [iter(iterable)] * n
return imap(None, *args)
If you need to go earlier than 2.3, you can substitute the built-in map for imap. The disadvantage is that it provides no ability to customize the fill value.
There is one addition perk of using re.compile(), in the form of adding comments to my regex patterns using re.VERBOSE
pattern = '''
hello[ ]world # Some info on my pattern logic. [ ] to recognize space
'''
re.search(pattern, 'hello world', re.VERBOSE)
Although this does not affect the speed of running your code, I like to do it this way as it is part of my commenting habit. I throughly dislike spending time trying to remember the logic that went behind my code 2 months down the line when I want to make modifications.
~Controller
namespace ListBindingTest.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
List<String> tmp = new List<String>();
tmp.Add("one");
tmp.Add("two");
tmp.Add("Three");
return View(tmp);
}
[HttpPost]
public ActionResult Send(IList<String> input)
{
return View(input);
}
}
}
~ Strongly Typed Index View
@model IList<String>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@using(Html.BeginForm("Send", "Home", "POST"))
{
@Html.EditorFor(x => x)
<br />
<input type="submit" value="Send" />
}
</div>
</body>
</html>
~ Strongly Typed Send View
@model IList<String>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Send</title>
</head>
<body>
<div>
@foreach(var element in @Model)
{
@element
<br />
}
</div>
</body>
</html>
This is all that you had to do man, change his MyViewModel model to IList.
Another option is to use SqlBulkTools available from Nuget. It's very easy to use and has some powerful features.
Example:
var bulk = new BulkOperations();
var books = GetBooks();
using (TransactionScope trans = new TransactionScope())
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager
.ConnectionStrings["SqlBulkToolsTest"].ConnectionString))
{
bulk.Setup<Book>()
.ForCollection(books)
.WithTable("Books")
.AddAllColumns()
.BulkInsert()
.Commit(conn);
}
trans.Complete();
}
See the documentation for more examples and advanced usage. Disclaimer: I am the author of this library and any views are of my own opinion.
Just pressing F5 is not always working.
why?
Because your ISP is also caching web data for you.
Solution: Force Refresh.
Force refresh your browser by pressing CTRL + F5 in Firefox or Chrome to clear ISP cache too, instead of just pressing F5
You then can see 200 response instead of 304 in the browser F12 developer tools network tab.
Another trick is to add question mark ?
at the end of the URL string of the requested page:
http://localhost:52199/Customers/Create?
The question mark will ensure that the browser refresh the request without caching any previous requests.
Additionally in Visual Studio you can set the default browser to Chrome in Incognito mode to avoid cache issues while developing, by adding Chrome in Incognito mode as default browser, see the steps (self illustrated):
it is different for different icons.(eg, diff sizes for action bar icons, laucnher icons, etc.) please follow this link icons handbook to learn more.
After viewing and changed the properties to DocumentFormat.OpenXml, I also had to change the Specific Version to false.
I had luck with something similar:
Convert(DATETIME, CONVERT(VARCHAR(2), @Month) + '/' + CONVERT(VARCHAR(2), @Day)
+ '/' + CONVERT(VARCHAR(4), @Year))
You probably want transparent
as none
is not a valid background-color
value.
The CSS 2.1 spec states the following for the background-color
property:
Value: <color> | transparent | inherit
<color>
can be either a keyword or a numerical representation of a colour. Valid color
keywords are:
aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, and yellow
transparent
and inherit
are valid keywords in their own right, but none
is not.
I found a better way of doing this
function genrateJSONEngine() {
var XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xlsx');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) {
var array = workbook.Sheets[y];
var first = array[0].join()
var headers = first.split(',');
var jsonData = [];
for (var i = 1, length = array.length; i < length; i++) {
var myRow = array[i].join();
var row = myRow.split(',');
var data = {};
for (var x = 0; x < row.length; x++) {
data[headers[x]] = row[x];
}
jsonData.push(data);
}
function getDirContents(string $dir, int $onlyFiles = 0, string $excludeRegex = '~/\.git/~', int $maxDepth = -1): array {
$results = [];
$scanAll = scandir($dir);
sort($scanAll);
$scanDirs = []; $scanFiles = [];
foreach($scanAll as $fName){
if ($fName === '.' || $fName === '..') { continue; }
$fPath = str_replace(DIRECTORY_SEPARATOR, '/', realpath($dir . '/' . $fName));
if (strlen($excludeRegex) > 0 && preg_match($excludeRegex, $fPath . (is_dir($fPath) ? '/' : ''))) { continue; }
if (is_dir($fPath)) {
$scanDirs[] = $fPath;
} elseif ($onlyFiles >= 0) {
$scanFiles[] = $fPath;
}
}
foreach ($scanDirs as $pDir) {
if ($onlyFiles <= 0) {
$results[] = $pDir;
}
if ($maxDepth !== 0) {
foreach (getDirContents($pDir, $onlyFiles, $excludeRegex, $maxDepth - 1) as $p) {
$results[] = $p;
}
}
}
foreach ($scanFiles as $p) {
$results[] = $p;
}
return $results;
}
function updateKeysWithRelPath(array $paths, string $baseDir, bool $allowBaseDirPath = false): array {
$results = [];
$regex = '~^' . preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', realpath($baseDir)), '~') . '(?:/|$)~s';
$regex = preg_replace('~/~', '/(?:(?!\.\.?/)(?:(?!/).)+/\.\.(?:/|$))?(?:\.(?:/|$))*', $regex); // limited to only one "/xx/../" expr
if (DIRECTORY_SEPARATOR === '\\') {
$regex = preg_replace('~/~', '[/\\\\\\\\]', $regex) . 'i';
}
foreach ($paths as $p) {
$rel = preg_replace($regex, '', $p, 1);
if ($rel === $p) {
throw new \Exception('Path relativize failed, path "' . $p . '" is not within basedir "' . $baseDir . '".');
} elseif ($rel === '') {
if (!$allowBaseDirPath) {
throw new \Exception('Path relativize failed, basedir path "' . $p . '" not allowed.');
} else {
$results[$rel] = './';
}
} else {
$results[$rel] = $p;
}
}
return $results;
}
function getDirContentsWithRelKeys(string $dir, int $onlyFiles = 0, string $excludeRegex = '~/\.git/~', int $maxDepth = -1): array {
return updateKeysWithRelPath(getDirContents($dir, $onlyFiles, $excludeRegex, $maxDepth), $dir);
}
realpath
when PHP open_basedir
does not cover the ..
directory.// list only `*.php` files and skip .git/ and the current file
$onlyPhpFilesExcludeRegex = '~/\.git/|(?<!/|\.php)$|^' . preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', realpath(__FILE__)), '~') . '$~is';
$phpFiles = getDirContents(__DIR__, 1, $onlyPhpFilesExcludeRegex);
print_r($phpFiles);
// with relative keys
$phpFiles = getDirContentsWithRelKeys(__DIR__, 1, $onlyPhpFilesExcludeRegex);
print_r($phpFiles);
// with "include only" regex to include only .html and .txt files with "/*_mails/en/*.(html|txt)" path
'~/\.git/|^(?!.*/(|' . '[^/]+_mails/en/[^/]+\.(?:html|txt)' . ')$)~is'
you can use update from...
something like:
update shipment set.... from shipment inner join ProfilerTest.dbo.BookingDetails on ...
If the key you are checking is stored in a variable, you can check it like this:
x = {'key': 1};
y = 'key';
x[y];
This is improved @Vicky solution - it has clearInterval() added so it prevents a loop of reloading if the redirect takes too long:
$(document).ready(function () {
var myTimer = window.setInterval(function () {
var timeLeft = $("#countdown").html();
if (eval(timeLeft) == 0) {
console.log('Now redirecting');
clearInterval(myTimer);
window.location = ("@Html.Raw(HttpUtility.HtmlDecode(redirectUrl))");
} else {
$("#countdown").html(eval(timeLeft) - eval(1));
}
}, 1000);
});
select your table -> view dependencies -> Objects that depend on
@RequestMapping(value = "/books", method = { RequestMethod.GET,
RequestMethod.POST })
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
HttpServletRequest request)
throws ParseException {
//your code
}
This will works for both GET and POST.
For GET if your pojo(BooksFilter) have to contain the attribute which you're using in request parameter
like below
public class BooksFilter{
private String parameter1;
private String parameter2;
//getters and setters
URl should be like below
/books?parameter1=blah
Like this way u can use it for both GET and POST
In laymen language we can say:
I've had success with using white-space: nowrap; on the outer container, display: inline-block; on the inner containers, and then (in my case since I wanted the second one to word-wrap) white-space: normal; on the inner ones.
I was scratching my head about this for a while too, and since Dave's explanation is a little hard to understand I'll post my (apparently working) code:
private class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private Activity mActivity;
private final String mTag;
private final Class<T> mClass;
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
mFragment=mActivity.getFragmentManager().findFragmentByTag(mTag);
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.replace(android.R.id.content, mFragment, mTag);
} else {
if (mFragment.isDetached()) {
ft.attach(mFragment);
}
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
As you can see it's pretty much like the Android sample, apart from not detaching in the constructor, and using replace instead of add.
After much headscratching and trial-and-error I found that finding the fragment in the constructor seems to make the double onCreateView problem magically go away (I assume it just ends up being null for onTabSelected when called through the ActionBar.setSelectedNavigationItem() path when saving/restoring state).
Use CSS to remove text-decoration
s.
a {
text-decoration: none;
}
Or
// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")
Both answers pulled from JavaScript equivalent to printf/string.format
None of the solutions above work perfectly.They either loses CSS or have to include/edit external CSS file. I found a perfect solution that will not lose your CSS nor you have to edit/add external CSS.
HTML:
<div id='printarea'>
<p>This is a sample text for printing purpose.</p>
<input type='button' id='btn' value='Print' onclick='printFunc();'>
</div>
<p>Do not print.</p
JQuery:
function printFunc() {
var divToPrint = document.getElementById('printarea');
var htmlToPrint = '' +
'<style type="text/css">' +
'table th, table td {' +
'border:1px solid #000;' +
'padding;0.5em;' +
'}' +
'</style>';
htmlToPrint += divToPrint.outerHTML;
newWin = window.open("");
newWin.document.write("<h3 align='center'>Print Page</h3>");
newWin.document.write(htmlToPrint);
newWin.print();
newWin.close();
}
If you are using OneDrive, or any similar network drive, you have 2 options:
1) the easy one is to move the folder to a local directory inside your PC (eg:. C:).
2) but if you want to keep using OneDrive I would recommend to add it to the trusted sites on the internet explorer options and that will fix the problem.
It is cd
for "current directory".
You can just add '\r' at the end of the string plus a comma at the end of print function. For example:
print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!\r'),
Even once you fixed the mis-cased if
and improper indentation in your code, it wouldn't work as you probably expected. To check a string against a set of strings, use in
. Here's how you'd do it (and note that if
is all lowercase and that the code within the if
block is indented one level).
One approach:
if answer in ['y', 'Y', 'yes', 'Yes', 'YES']:
print("this will do the calculation")
Another:
if answer.lower() in ['y', 'yes']:
print("this will do the calculation")
Complete working example in Kotlin, I have replaced my API keys with 1111...
val apiService = API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
val params = HashMap<String, String>()
params["q"] = "munich,de"
params["APPID"] = "11111111111111111"
val call = apiService.getWeather(params)
call.enqueue(object : Callback<WeatherResponse> {
override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
Log.e("Error:::","Error "+t!!.message)
}
override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
if (response != null && response.isSuccessful && response.body() != null) {
Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)
temperature.setText(""+ response.body()!!.main.temp)
}
}
})
Using Visual Studio's Productivity Power Tools (free) extension helps a bit. Specifically, the Solution Error Visualizer
feature. With it, compilation errors marked visually in the solution explorer (in the source file where the error was found). For some reason, however, this feature does not work as with other errors anywhere else in the code.
With MVC views, any compile-time errors will still be underlined in red in their respective .cs files, but signaling these errors is not propagated upwards in the Solution Explorer (in no way, even not in the containing source file).
Thanks for BlueClouds
for correcting my previous statement.
I have just reported this as an issue on the extension's github project.
ok, an other one with regexp - probably not fast, but short and better readable then others, in my case just '_'
to count
key.replace(/[^_]/g,'').length
just remove everything that does not look like your char but it does not look nice with a string as input
What your statements are telling you is just that "" isn't the same as null - which is true. "" is an empty string; null means that no value has been assigned.
It might be more enlightening to try:
System.out.println(a.length()); // 0
System.out.println(b.length()); // error; b is not an object
"" is still a string, meaning you can call its methods and get meaningful information. null is an empty variable - there's literally nothing there.
Building on other answers, a simple solution based on a specific serializer that just converts datetime.datetime
and datetime.date
objects to strings.
from datetime import date, datetime
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError ("Type %s not serializable" % type(obj))
As seen, the code just checks to find out if object is of class datetime.datetime
or datetime.date
, and then uses .isoformat()
to produce a serialized version of it, according to ISO 8601 format, YYYY-MM-DDTHH:MM:SS (which is easily decoded by JavaScript). If more complex serialized representations are sought, other code could be used instead of str() (see other answers to this question for examples). The code ends by raising an exception, to deal with the case it is called with a non-serializable type.
This json_serial function can be used as follows:
from datetime import datetime
from json import dumps
print dumps(datetime.now(), default=json_serial)
The details about how the default parameter to json.dumps works can be found in Section Basic Usage of the json module documentation.
Assuming that yourObject.toString() returns "true" or "false", you can try
boolean b = Boolean.valueOf(yourObject.toString())
import java.lang.String;
This is an unnecessary import. java.lang classes are always implicitly imported. This means that you do not have to import them manually (explicitly).
Firstly, you start Activities and Services with an intent, you start fragments with fragment transactions. Secondly, your transaction isnt doing anything. Change it to something like:
FragmentTransaction transaction = getFragmentManager();
transaction.beginTransaction()
.replace(R.layout.container, newFragment) //<---replace a view in your layout (id: container) with the newFragment
.commit();
I was getting this error when running a remote development development machine using Vagrant. None of the above solutions worked because all the files had the correct permissions.
I fixed it by changing config.vm.box = "hasicorp/bionic64"
to config.vm.box = "bento/ubuntu-20.10"
.
You need to create an user "ODBC" for MySql with no password. Do that in PHPMyAdmin. That will solve your problem.
But remember, if it's only your local development environment, no problem. It'll create a serious security hole in your production environment.
My open source application BugTracker.NET includes a POP3 client that can parse MIME. Both the POP3 code and the MIME code are from other authors, but you can see how it all fits together in my app.
For the MIME parsing, I use http://anmar.eu.org/projects/sharpmimetools/.
See the file POP3Main.cs, POP3Client.cs, and insert_bug.aspx
Most of all has posted correct answer. I would like to add few links, so that you can refer to them and have clear and better ideas about the same:
UserControl: http://msdn.microsoft.com/en-IN/library/a6h7e207(v=vs.71).aspx
The difference between page and window with respect to WPF: Page vs Window in WPF?
What we have in our table:-
Primary Key
Event type (e.g. "UPDATED", "APPROVED")
Description ("Frisbar was added to blong")
User Id
User Id of second authoriser
Amount
Date/time
Generic Id
Table Name
The generic id points at a row in the table that was updated and the table name is the name of that table as a string. Not a good DB design, but very usable. All our tables have a single surrogate key column so this works well.
If you only care about unimodal distributions, consider sth. like this.
public static Optional<Integer> mode(Stream<Integer> stream) {
Map<Integer, Long> frequencies = stream
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
return frequencies.entrySet().stream()
.max(Comparator.comparingLong(Map.Entry::getValue))
.map(Map.Entry::getKey);
}
If you had permission from the content owners of the videos to upload copies in your own account, and then ensured that your account was set up with monetization turned off, then that would prevent ads from showing during playback. It's up to you to work out that arrangement/permission with the original videos' owners, of course.
(It's also worth pointing out that if your goal is to help non-profits raise money, then allowing them to monetize their video playbacks is in line with that goal...)
Visual Basic has built-in constants for newlines:
vbCr
= Chr$(13) = CR (carriage-return character) - used by Mac OS and Apple II family
vbLf
= Chr$(10) = LF (line-feed character) - used by Linux and Mac OS X
vbCrLf
= Chr$(13) & Chr$(10) = CRLF (carriage-return followed by line-feed) - used by Windows
vbNewLine
= the same as vbCrLf
Try this:
private void cmbLineColor_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView drv = (DataRowView)cmbLineColor.SelectedItem;
int selectedValue = (int)drv.Row.ItemArray[1];
}
Update maven version to 3.6.3 and run
mvn -Dhttps.protocols=TLSv1.2 install
it worked on centos 6.9
Use subscripting to access the value for a dictionary key. This will return an Optional:
let apple: String? = companies["AAPL"]
or
if let apple = companies["AAPL"] {
// ...
}
You can also enumerate over all of the keys and values:
var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]
for (key, value) in companies {
print("\(key) -> \(value)")
}
Or enumerate over all of the values:
for value in Array(companies.values) {
print("\(value)")
}
Maybe slight overkill but created library ngx-if-empty-or-has-items it checks if an object, set, map or array is not empty. Maybe it will help somebody. It has the same functionality as ngIf (then, else and 'as' syntax is supported).
arrayOrObjWithData = ['1'] || {id: 1}
<h1 *ngxIfNotEmpty="arrayOrObjWithData">
You will see it
</h1>
or
// store the result of async pipe in variable
<h1 *ngxIfNotEmpty="arrayOrObjWithData$ | async as obj">
{{obj.id}}
</h1>
or
noData = [] || {}
<h1 *ngxIfHasItems="noData">
You will NOT see it
</h1>
You could do it in either of this ways , triggering an onclick
on a form button like this,
<form id="myform" name="myform" method="post" action="demo2.jsp">
<input type="text" name="usnername" />
<input type="text" name="password"/>
<input type="button" value="go" onclick="submitForm" />
</form>
And using javascript
,
function submitForm() {
document.forms[0].submit();
return true;
}
or you could also try Ajax
to post your page
here is the link jQueryAjax
And also nice startup examples using Ajax and here
Hope this helps !!
As others said, Stopwatch
should be the right tool for this. There can be few improvements made to it though, see this thread specifically: Benchmarking small code samples in C#, can this implementation be improved?.
I have seen some useful tips by Thomas Maierhofer here
Basically his code looks like:
//prevent the JIT Compiler from optimizing Fkt calls away
long seed = Environment.TickCount;
//use the second Core/Processor for the test
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2);
//prevent "Normal" Processes from interrupting Threads
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
//prevent "Normal" Threads from interrupting this thread
Thread.CurrentThread.Priority = ThreadPriority.Highest;
//warm up
method();
var stopwatch = new Stopwatch()
for (int i = 0; i < repetitions; i++)
{
stopwatch.Reset();
stopwatch.Start();
for (int j = 0; j < iterations; j++)
method();
stopwatch.Stop();
print stopwatch.Elapsed.TotalMilliseconds;
}
Another approach is to rely on Process.TotalProcessTime
to measure how long the CPU has been kept busy running the very code/process, as shown here This can reflect more real scenario since no other process affects the measurement. It does something like:
var start = Process.GetCurrentProcess().TotalProcessorTime;
method();
var stop = Process.GetCurrentProcess().TotalProcessorTime;
print (end - begin).TotalMilliseconds;
A naked, detailed implementation of the samething can be found here.
I wrote a helper class to perform both in an easy to use manner:
public class Clock
{
interface IStopwatch
{
bool IsRunning { get; }
TimeSpan Elapsed { get; }
void Start();
void Stop();
void Reset();
}
class TimeWatch : IStopwatch
{
Stopwatch stopwatch = new Stopwatch();
public TimeSpan Elapsed
{
get { return stopwatch.Elapsed; }
}
public bool IsRunning
{
get { return stopwatch.IsRunning; }
}
public TimeWatch()
{
if (!Stopwatch.IsHighResolution)
throw new NotSupportedException("Your hardware doesn't support high resolution counter");
//prevent the JIT Compiler from optimizing Fkt calls away
long seed = Environment.TickCount;
//use the second Core/Processor for the test
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2);
//prevent "Normal" Processes from interrupting Threads
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
//prevent "Normal" Threads from interrupting this thread
Thread.CurrentThread.Priority = ThreadPriority.Highest;
}
public void Start()
{
stopwatch.Start();
}
public void Stop()
{
stopwatch.Stop();
}
public void Reset()
{
stopwatch.Reset();
}
}
class CpuWatch : IStopwatch
{
TimeSpan startTime;
TimeSpan endTime;
bool isRunning;
public TimeSpan Elapsed
{
get
{
if (IsRunning)
throw new NotImplementedException("Getting elapsed span while watch is running is not implemented");
return endTime - startTime;
}
}
public bool IsRunning
{
get { return isRunning; }
}
public void Start()
{
startTime = Process.GetCurrentProcess().TotalProcessorTime;
isRunning = true;
}
public void Stop()
{
endTime = Process.GetCurrentProcess().TotalProcessorTime;
isRunning = false;
}
public void Reset()
{
startTime = TimeSpan.Zero;
endTime = TimeSpan.Zero;
}
}
public static void BenchmarkTime(Action action, int iterations = 10000)
{
Benchmark<TimeWatch>(action, iterations);
}
static void Benchmark<T>(Action action, int iterations) where T : IStopwatch, new()
{
//clean Garbage
GC.Collect();
//wait for the finalizer queue to empty
GC.WaitForPendingFinalizers();
//clean Garbage
GC.Collect();
//warm up
action();
var stopwatch = new T();
var timings = new double[5];
for (int i = 0; i < timings.Length; i++)
{
stopwatch.Reset();
stopwatch.Start();
for (int j = 0; j < iterations; j++)
action();
stopwatch.Stop();
timings[i] = stopwatch.Elapsed.TotalMilliseconds;
print timings[i];
}
print "normalized mean: " + timings.NormalizedMean().ToString();
}
public static void BenchmarkCpu(Action action, int iterations = 10000)
{
Benchmark<CpuWatch>(action, iterations);
}
}
Just call
Clock.BenchmarkTime(() =>
{
//code
}, 10000000);
or
Clock.BenchmarkCpu(() =>
{
//code
}, 10000000);
The last part of the Clock
is the tricky part. If you want to display the final timing, its up to you to choose what sort of timing you want. I wrote an extension method NormalizedMean
which gives you the mean of the read timings discarding the noise. I mean I calculate the the deviation of each timing from the actual mean, and then I discard the values which was farer (only the slower ones) from the mean of deviation (called absolute deviation; note that its not the often heard standard deviation), and finally return the mean of remaining values. This means, for instance, if timed values are { 1, 2, 3, 2, 100 }
(in ms or whatever), it discards 100
, and returns the mean of { 1, 2, 3, 2 }
which is 2
. Or if timings are { 240, 220, 200, 220, 220, 270 }
, it discards 270
, and returns the mean of { 240, 220, 200, 220, 220 }
which is 220
.
public static double NormalizedMean(this ICollection<double> values)
{
if (values.Count == 0)
return double.NaN;
var deviations = values.Deviations().ToArray();
var meanDeviation = deviations.Sum(t => Math.Abs(t.Item2)) / values.Count;
return deviations.Where(t => t.Item2 > 0 || Math.Abs(t.Item2) <= meanDeviation).Average(t => t.Item1);
}
public static IEnumerable<Tuple<double, double>> Deviations(this ICollection<double> values)
{
if (values.Count == 0)
yield break;
var avg = values.Average();
foreach (var d in values)
yield return Tuple.Create(d, avg - d);
}
You could try in this way.
SOAPMessage msg = messageContext.getMessage();
ByteArrayOutputStream out = new ByteArrayOutputStream();
msg.writeTo(out);
String strMsg = new String(out.toByteArray());
db.Database.SqlQuery<myEntityType>("exec GetNewSeqOfFoodServing @p0,@p1,@p2 ", foods_WEIGHT.NDB_No, HLP.CuntryID, HLP.ClientID).Single()
or
db.Database.SqlQuery<myEntityType>(
"exec GetNewSeqOfFoodServing @param1, @param2",
new SqlParameter("param1", param1),
new SqlParameter("param2", param2)
);
or
var cmdText = "exec [DoStuff] @Name = @name_param, @Age = @age_param";
var @params = new[]{
new SqlParameter("name_param", "Josh"),
new SqlParameter("age_param", 45)
};
db.Database.SqlQuery<myEntityType>(cmdText, @params)
or
db.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
new object[] { param1, param2, param3 }).ToList();
I know this is an old post but maybe someone down the line can use this.
// use document.form["form-name"] to reference the form
const ccForm = document.forms["ccform"];
// bind the onsubmit property to a function to do some logic
ccForm.onsubmit = function(e) {
// access the desired input through the var we setup
let ccSelection = ccForm.ccselect.value;
console.log(ccSelection);
e.preventDefault();
}
_x000D_
<form name="ccform">
<select name="ccselect">
<option value="card1">Card 1</option>
<option value="card2">Card 2</option>
<option value="card3">Card 3</option>
</select>
<button type="submit">Enter</button>
</form>
_x000D_
Just saying for those who using Imagick class in PHP:
$im -> gaussianBlurImage(0.8, 10); //blur
$im -> setImageCompressionQuality(85); //set compress quality to 85
$float = -abs($float);
If you are verifying if a lock is applied on a table or not, try the below query.
SELECT resource_type, resource_associated_entity_id,
request_status, request_mode,request_session_id,
resource_description, o.object_id, o.name, o.type_desc
FROM sys.dm_tran_locks l, sys.objects o
WHERE l.resource_associated_entity_id = o.object_id
and resource_database_id = DB_ID()
The ternary operator can only be the right side of an assignment and not a statement of its own.
For Visual Studio/Express 2010 only. See other (easier) answers for VS2012, VS2013, etc
To find the missing file(s), use info from the article Enable C++ project system logging to enable debug logging in Visual Studio and let it just tell you what's causing the rebuild:
devenv.exe.config
file (found in %ProgramFiles%\Microsoft Visual Studio 10.0\Common7\IDE\
or in %ProgramFiles(x86)%\Microsoft Visual Studio 10.0\Common7\IDE\
). For Express versions the config file is named V*Express.exe.config
.Add the following after the </configSections>
line:
<system.diagnostics>
<switches>
<add name="CPS" value="4" />
</switches>
</system.diagnostics>
Search the debug log for any lines of the form:
devenv.exe Information: 0 : Project 'Bla\Bla\Dummy.vcxproj' not up to date because build input 'Bla\Bla\SomeFile.h' is missing.
(I just hit Ctrl+F and searched for not up to date
) These will be the references causing the project to be perpetually "out of date".
To correct this, either remove any references to the missing files from your project, or update the references to indicate their actual locations.
Note: If using 2012 or later then the snippet should be:
<system.diagnostics>
<switches>
<add name="CPS" value="Verbose" />
</switches>
</system.diagnostics>
I found an excellent (and tested) way to check for valid email address. I paste my code here:
# here i import the module that implements regular expressions
import re
# here is my function to check for valid email address
def test_email(your_pattern):
pattern = re.compile(your_pattern)
# here is an example list of email to check it at the end
emails = ["[email protected]", "[email protected]", "wha.t.`1an?ug{}[email protected]"]
for email in emails:
if not re.match(pattern, email):
print "You failed to match %s" % (email)
elif not your_pattern:
print "Forgot to enter a pattern!"
else:
print "Pass"
# my pattern that is passed as argument in my function is here!
pattern = r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?"
# here i test my function passing my pattern
test_email(pattern)
Here is how you can do it with a socket on php-fpm 7
install socat
apt-get install socat
#!/bin/sh
if echo /dev/null | socat UNIX:/var/run/php/php7.0-fpm.sock - ; then
echo "$home/run/php-fpm.sock connect OK"
else
echo "$home/run/php-fpm.sock connect ERROR"
fi
You can also check if the service is running like this.
service php7.0-fpm status | grep running
It will return
Active: active (running) since Sun 2017-04-09 12:48:09 PDT; 48s ago
The complement of a regular language is also a regular language, but to construct it you have to build the DFA for the regular language, and make any valid state change into an error. See this for an example. What the page doesn't say is that it converted /(ac|bd)/
into /(a[^c]?|b[^d]?|[^ab])/
. The conversion from a DFA back to a regular expression is not trivial. It is easier if you can use the regular expression unchanged and change the semantics in code, like suggested before.
Under your main views.py
add your own custom implementation of the following two views, and just set up the templates 404.html and 500.html with what you want to display.
With this solution, no custom code needs to be added to urls.py
Here's the code:
from django.shortcuts import render_to_response
from django.template import RequestContext
def handler404(request, *args, **argv):
response = render_to_response('404.html', {},
context_instance=RequestContext(request))
response.status_code = 404
return response
def handler500(request, *args, **argv):
response = render_to_response('500.html', {},
context_instance=RequestContext(request))
response.status_code = 500
return response
Update
handler404
and handler500
are exported Django string configuration variables found in django/conf/urls/__init__.py
. That is why the above config works.
To get the above config to work, you should define the following variables in your urls.py
file and point the exported Django variables to the string Python path of where these Django functional views are defined, like so:
# project/urls.py
handler404 = 'my_app.views.handler404'
handler500 = 'my_app.views.handler500'
Update for Django 2.0
Signatures for handler views were changed in Django 2.0: https://docs.djangoproject.com/en/2.0/ref/views/#error-views
If you use views as above, handler404 will fail with message:
"handler404() got an unexpected keyword argument 'exception'"
In such case modify your views like this:
def handler404(request, exception, template_name="404.html"):
response = render_to_response(template_name)
response.status_code = 404
return response
[Edit] This answer is for MSVS (the IDE, as opposed to VS Code). It seems Microsoft and Google go out of their way to choose confusing names for new products. I'll leave this answer here for now, while I (continue to) look for the equivalent stackoverflow question about MSVS. Let me know in the comments if you think I should delete it. Or better, point me to the MSVS version of this question.
I installed MSVS 2017 recently. None of the suggestions I've seen fixed the problem. The solution I figured out works for MSVS 2015 and 2017. Add a comment below if you find that it works for other versions.
Under Tools -> Options -> Text Editor -> C/C++ -> Formatting -> General, try unchecking the "Automatically indent when I type a tab" box. It seems counter intuitive, but it fixed the problem for me.
Let me share what I end up with, which allows to set correctly width or height by getting the image dimensions. In addition, the code allows to fetch a loading image while the large image data we need is being transfered:
Use static method Image.prefetch to have the image downloaded and available to cache.
Use static method Image.getSize to collect height and width and use it to compute an aspect ratio and then the final height (or width)
Display image with a default style to your prefered width (The height will be computed with aspect ratio kept)
function ImageX(props: {source: string, id: string})
{
const [imageHeight, setImageHeight] = React.useState(1);
Image.prefetch(props.source)
.then(() => {
Image.getSize(props.source, (width, height) => {
let aspectRatio = height/width;
setImageHeight(aspectRatio*Dimensions.get('window').width);
});
})
.catch(error => console.log(error))
if (imageHeight <=1) //Image not in cache (disk) yet
{
return (
<Image key={props.id} style={styleimg.image} source={{uri: 'http://www.dsdsd/loaderpreview.gif'}}/>
);
}
else
{
return (
<Image key={props.id} style={styleimg.image} height={imageHeight} source={{uri: props.source}}/>
);
}
}
const styleimg = StyleSheet.create({ image: { width: Dimensions.get('window').width, resizeMode: 'contain' //... // you can set a height defaults } });
I'm guessing your code failed BEFORE import sys, so it can't find it when you handle the exception.
Also, you should indent the your code whithin the try
block.
try:
import sys
# .. other safe imports
try:
import numpy as np
# other unsafe imports
except ImportError:
print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
sys.exit()
Set style= "display:none;"
. By setting visible=false
, it will not render button in the browser. Thus,client side script wont execute.
<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />
html markup should be
<button id="btnsave" onclick="fncsave()">Save</button>
Change javascript to
<script type="text/javascript">
function fncsave()
{
document.getElementById('<%= savebtn.ClientID %>').click();
}
</script>
Sub SelectAllCellsInSheet(SheetName As String)
lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub
To use with ActiveSheet:
Call SelectAllCellsInSheet(ActiveSheet.Name)
It looks like you're comparing strings incorrectly. To compare a string to another, use the std::string::compare
function.
Example
while ((wrong < MAX_WRONG) && (soFar.compare(THE_WORD) != 0))
Ctrl + F11 works wonderfully on Ubuntu / Linux Mint.
The first is better. If you try to debug the second and look at the call stack you won't see where the original exception came from. There are tricks to keep the call-stack intact (try search, it's been answered before) if you really need to rethrow.
There is no way to create a file without opening it There is os.mknod("newfile.txt")
(but it requires root privileges on OSX). The system call to create a file is actually open()
with the O_CREAT
flag. So no matter how, you'll always open the file.
So the easiest way to simply create a file without truncating it in case it exists is this:
open(x, 'a').close()
Actually you could omit the .close()
since the refcounting GC of CPython will close it immediately after the open()
statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.
In case you want touch
's behaviour (i.e. update the mtime in case the file exists):
import os
def touch(path):
with open(path, 'a'):
os.utime(path, None)
You could extend this to also create any directories in the path that do not exist:
basedir = os.path.dirname(path)
if not os.path.exists(basedir):
os.makedirs(basedir)
Trying using :
imageview.setFitToScreen(true);
imageview.setScaleType(ScaleType.FIT_CENTER);
This will fit your imageview to the screen with the correct ratio.
I recommend reading this post.
When using AnyCPU, the semantics are the following:
- If the process runs on a 32-bit Windows system, it runs as a 32-bit process. CIL is compiled to x86 machine code.
- If the process runs on a 64-bit Windows system, it runs as a 32-bit process. CIL is compiled to x86 machine code.
- If the process runs on an ARM Windows system, it runs as a 32-bit process. CIL is compiled to ARM machine code.
Used the following along with DefaultTrustManager and it worked in httpclient like charm. Thanks a ton!! @Kevin and every other contributor
SSLContext ctx = null;
SSLConnectionSocketFactory sslsf = null;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
sslsf = new SSLConnectionSocketFactory(
ctx,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
} catch (Exception e) {
e.printStackTrace();
}
CloseableHttpClient client = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
I always use pseudo elements :before
and :after
for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
Steps
visibility:hidden
or opacity:0
or position:absolute;left:-9999px
etc.:before
element and pass either an empty or a non-breaking space '\00a0'
;:checked
state, pass the unicode content: "\2713"
, which is a checkmark;:focus
style to make the checkbox accessible.Here is how I did it.
.box {_x000D_
background: #666666;_x000D_
color: #ffffff;_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
margin: 1.5em 0;_x000D_
padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
visibility: hidden;_x000D_
}_x000D_
label {_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
border: 1px solid #333;_x000D_
content: "\00a0";_x000D_
display: inline-block;_x000D_
font: 16px/1em sans-serif;_x000D_
height: 16px;_x000D_
margin: 0 .25em 0 0;_x000D_
padding: 0;_x000D_
vertical-align: top;_x000D_
width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
background: #fff;_x000D_
color: #333;_x000D_
content: "\2713";_x000D_
text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
<div class="box">_x000D_
<p>_x000D_
<input type="checkbox" id="c1" name="cb">_x000D_
<label for="c1">Option 01</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c2" name="cb">_x000D_
<label for="c2">Option 02</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c3" name="cb">_x000D_
<label for="c3">Option 03</label>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
Much more stylish using :before
and :after
body{_x000D_
font-family: sans-serif; _x000D_
}_x000D_
_x000D_
.container {_x000D_
margin-top: 50px;_x000D_
margin-left: 20px;_x000D_
margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
width: 100%;_x000D_
margin: 15px auto;_x000D_
position: relative;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
width: auto;_x000D_
opacity: 0.00000001;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
margin: 4px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
transition: transform 0.28s ease;_x000D_
border-radius: 3px;_x000D_
border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
content: '';_x000D_
display: block;_x000D_
width: 10px;_x000D_
height: 5px;_x000D_
border-bottom: 2px solid #7bbe72;_x000D_
border-left: 2px solid #7bbe72;_x000D_
-webkit-transform: rotate(-45deg) scale(0);_x000D_
transform: rotate(-45deg) scale(0);_x000D_
transition: transform ease 0.25s;_x000D_
will-change: transform;_x000D_
position: absolute;_x000D_
top: 12px;_x000D_
left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
-webkit-transform: rotate(-45deg) scale(1);_x000D_
transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
min-height: 34px;_x000D_
display: block;_x000D_
padding-left: 40px;_x000D_
margin-bottom: 0;_x000D_
font-weight: normal;_x000D_
cursor: pointer;_x000D_
vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
-webkit-transform: translateY(-50%);_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox" name="" value="">_x000D_
<label for="checkbox"><span>Checkbox</span></label>_x000D_
</div>_x000D_
_x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox2" name="" value="">_x000D_
<label for="checkbox2"><span>Checkbox</span></label>_x000D_
</div>_x000D_
</div>
_x000D_
I can't tell you how this is possible with classes, but functions can delete themselves.
def kill_self(exit_msg = 'killed'):
global kill_self
del kill_self
return exit_msg
And see the output:
>>> kill_self
<function kill_self at 0x02A2C780>
>>> kill_self()
'killed'
>>> kill_self
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
kill_self
NameError: name 'kill_self' is not defined
I don't think that deleting an individual instance of a class without knowing the name of it is possible.
NOTE: If you assign another name to the function, the other name will still reference the old one, but will cause errors once you attempt to run it:
>>> x = kill_self
>>> kill_self()
>>> kill_self
NameError: name 'kill_self' is not defined
>>> x
<function kill_self at 0x...>
>>> x()
NameError: global name 'kill_self' is not defined
As mentioned by @physicsGuy above, You can use the hinterland extension. Simple steps to do it.
Installing nbextension using conda forge channel. Simply run the below command in conda terminal:
conda install -c conda-forge jupyter_nbextensions_configurator
Next Step enabling the hinterland extension. Run the below command in conda terminal:
jupyter nbextension enable hinterland/hinterland
That's it, done.
Dim distinctValues As List(Of Double) = (From r In _
DirectCast(DataTable.AsEnumerable(),IEnumerable(Of DataRow)) Where (Not r.IsNull("ColName")) _
Select r.Field(Of Double)("ColName")).Distinct().ToList()
This reply may be late but it may help users having similar problem. The opencv-contrib (available at https://github.com/opencv/opencv_contrib/releases) contains extra modules but the build procedure has to be done from core opencv (available at from https://github.com/opencv/opencv/releases) modules.
Follow below steps (assuming you are building it using CMake GUI)
Download openCV (from https://github.com/opencv/opencv/releases) and unzip it somewhere on your computer. Create build folder inside it
Download exra modules from OpenCV. (from https://github.com/opencv/opencv_contrib/releases). Ensure you download the same version.
Unzip the folder.
Open CMake
Click Browse Source and navigate to your openCV folder.
Click Browse Build and navigate to your build Folder.
Click the configure button. You will be asked how you would like to generate the files. Choose Unix-Makefile from the drop down menu and Click OK. CMake will perform some tests and return a set of red boxes appear in the CMake Window.
Search for "OPENCV_EXTRA_MODULES_PATH" and provide the path to modules folder (e.g. /Users/purushottam_d/Programs/OpenCV3_4_5_contrib/modules)
Click Configure again, then Click Generate.
Go to build folder
# cd build
# make
# sudo make install
Strangely importing directly from $_SESSION not working but have to do this to make it work :
<?php
$phpVar = $_SESSION['var'];
?>
<script>
var variableValue= '<?php echo $phpVar; ?>';
var imported = document.createElement('script');
imported.src = './your/path/to.js';
document.head.appendChild(imported);
</script>
and in to.js
$(document).ready(function(){
alert(variableValue);
// rest of js file
try to use following command
php artisan db:seed --class=DatabaseSeeder
Use concat() function instead of +
like this:
select concat(firstname, lastname) as "Name" from test.student
On Windows:
To get started, open the command prompt by clicking on Start and then typing cmd. In the command window, go ahead and type in the following command:
netstat -a -n -o
In the command above, the -o parameter is what will add the PID to the end of the table. Press enter and you should see something like this:
Now to see the name of the process that is using that port, go to Task Manager by pressing CTRL + SHIFT + ESC and then click on the Process tab. In Windows 10, you should click on the Details tab.
By default, the task manager does not display the process ID, so you have to click on View and then Select Columns.
You might also need to look into services running in background. To do that right-click and select open services as shown below:
Hope it helps :)
Yes, It should be alright to have both versions installed. It's actually pretty much expected nowadays. A lot of stuff is written in 2.7, but 3.5 is becoming the norm. I would recommend updating all your python to 3.5 ASAP, though.
You can also make sure that Eclipse has all of the updated changes. To do this, right-click your project and then press the "Refresh" menu item.
First thing to do is run this:
SHOW GRANTS;
You will quickly see you were assigned the anonymous user to authenticate into mysql.
Instead of logging into mysql with
mysql
login like this:
mysql -uroot
By default, root@localhost has all rights and no password.
If you cannot login as root without a password, do the following:
Step 01) Add the two options in the mysqld section of my.ini:
[mysqld]
skip-grant-tables
skip-networking
Step 02) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 03) Connect to mysql
mysql
Step 04) Create a password from root@localhost
UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit
Step 05) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 06) Login as root with password
mysql -u root -p
You should be good from there.
No need to use grep. ps
in Android can filter by COMM
value (last 15 characters of the package name in case of java app)
Let's say we want to check if com.android.phone
is running:
adb shell ps m.android.phone
USER PID PPID VSIZE RSS WCHAN PC NAME
radio 1389 277 515960 33964 ffffffff 4024c270 S com.android.phone
Filtering by COMM
value option has been removed from ps
in Android 7.0. To check for a running process by name in Android 7.0 you can use pidof
command:
adb shell pidof com.android.phone
It returns the PID if such process was found or an empty string otherwise.
You can check Visual Studio Downloads for available Visual Studio Community
, Visual Studio Professional
, Visual Studio Enterprise
and Visual Studio Code
download links.
Update!
There is no direct links of Visual Studio 2015
at Visual Studio Downloads anymore. but the below links still works.
OR simply click on direct links below (for .iso/.exe file):
VSCode area:
I came across this post while hunting down a solution for myself. By using chrome's inspector, I was able to determine that the striped color was being applied from the --bs-table-striped-color
tag.
overriding that tag in your css:
<style scoped>
table {
--bs-table-striped-color: #85d1ee;
}
</style>
The magic you have been looking for has been added in Rails 6
Now you can upsert (update or insert).
For single record use:
Model.upsert(column_name: value)
For multiple records use upsert_all :
Model.upsert_all(column_name: value, unique_by: :column_name)
Note:
With jquery you have other option:
$('head').html($('head').html() + '...');
anyway it is working. JavaScript option others said, thats correct too.
Since i have not faced this issue , I am taking a hunch --
Can you please try this :
Where does the soft link "java_home" point to :
ls -lrt /usr/libexec/java_home
Output : (Stunted) lrwxr-xr-x java_home -> /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java_home
**ls -lrt /System/Library/Frameworks/JavaVM.framework/Versions My MAC Produces the following :
lrwxr-xr-x CurrentJDK ->
/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents**
lrwxr-xr-x Current -> A
lrwxr-xr-x 1 root wheel 10 Oct 18 14:39 1.6.0 -> CurrentJDK
lrwxr-xr-x 1 root wheel 10 Oct 18 14:39 1.6 -> CurrentJDK
lrwxr-xr-x 1 root wheel 10 Oct 18 14:39 1.5.0 -> CurrentJDK
lrwxr-xr-x 1 root wheel 10 Oct 18 14:39 1.5 -> CurrentJDK
lrwxr-xr-x 1 root wheel 10 Oct 18 14:39 1.4.2 -> CurrentJDK
lrwxr-xr-x 1 root wheel 10 Oct 18 14:39 1.4 -> CurrentJDK
Based on this , we might get a hint to proceed further ?
Swapping the values from 1st position to till the end of the list, this code loops for ( n*n-1)/2 times. Each time it pushes the greater value to the greater index starting from Zero index.
list2 = [40,-5,10,2,0,-4,-10]
for l in range(len(list2)):
for k in range(l+1,len(list2)):
if list2[k] < list2[l]:
list2[k] , list2[l] = list2[l], list2[k]
print(list2)
You can try:
Open sql file by text editor find and replace all
utf8mb4 to utf8
Import again.
As referenced in my answer to Applying rounded corners to paths/polygons, I have written a routine in javascript for generically rounding corners of SVG paths, with examples, here: http://plnkr.co/edit/kGnGGyoOCKil02k04snu.
It will work independently from any stroke effects you may have. To use, include the rounding.js file from the Plnkr and call the function like so:
roundPathCorners(pathString, radius, useFractionalRadius)
The result will be the rounded path.
The results look like this:
Below code will delete the entire contents of artifact_path
- name: Clean artifact path
file:
state: absent
path: "{{ artifact_path }}/"
Note: this will delete the directory too.
Installing Java on macOS 11 Big Sur
:
JDK
(about 190 MB), which will put the OpenJDK11U-jdk_x64_mac_hotspot_11.0.9_11.pkg
file into your ~/Downloads folder
/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk
java --version
openjdk 11.0.9.1 2020-11-04
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.9.1+1)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.9.1+1, mixed mode)
JAVA_HOME
is an important environment variable and it’s important to get it right. Here is a trick that allows me to keep the environment variable current, even after a Java Update was installed. In ~/.zshrc
, I set the variable like so: export JAVA_HOME=$(/usr/libexec/java_home)
~/.bash_profile
. Anyway, open a new terminal and verify: echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home
TEST: Compile and Run your Java Program
HelloStackoverflow.java
.public class HelloStackoverflow {
public static void main(String[] args){
System.out.println("Hello Stackoverflow !");
}//End of main
}//End of HelloStackoverflow Class
HelloStackoverflow.java
, then type the command:javac HelloStackoverflow.java
If you're lucky, nothing will happen
Actually, a lot happened. javac
is the name of the Java compiler. It translates Java into Java Bytecode
, an assembly language for the Java Virtual Machine (JVM). The Java Bytecode is stored in a file called HelloStackoverflow.class
.
Running: type the command:
java HelloStackoverflow
# output:
# Hello Stackoverflow !
Regardless of following a naming convention that avoids using reserved words, Microsoft does add new reserved words. Using brackets allows your code to be upgraded to a new SQL Server version, without first needing to edit Microsoft's newly reserved words out of your client code. That editing can be a significant concern. It may cause your project to be prematurely retired....
Brackets can also be useful when you want to Replace All in a script. If your batch contains a variable named @String and a column named [String], you can rename the column to [NewString], without renaming @String to @NewString.
Yes.
Constructors are nothing more than special methods, and can throw exceptions like any other method.
Yes, excluding anonymous classes, readability and intent declaration it's almost worthless. Are those three things worthless though?
Personally I tend not to use final
for local variables and parameters unless I'm using the variable in an anonymous inner class, but I can certainly see the point of those who want to make it clear that the parameter value itself won't change (even if the object it refers to changes its contents). For those who find that adds to readability, I think it's an entirely reasonable thing to do.
Your point would be more important if anyone were actually claiming that it did keep data constant in a way that it doesn't - but I can't remember seeing any such claims. Are you suggesting there's a significant body of developers suggesting that final
has more effect than it really does?
EDIT: I should really have summed all of this up with a Monty Python reference; the question seems somewhat similar to asking "What have the Romans ever done for us?"
I have created LoadMoreRecyclerView using Abdulaziz Noor Answer
LoadMoreRecyclerView
public class LoadMoreRecyclerView extends RecyclerView {
private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;
//WrapperLinearLayout is for handling crash in RecyclerView
private WrapperLinearLayout mLayoutManager;
private Context mContext;
private OnLoadMoreListener onLoadMoreListener;
public LoadMoreRecyclerView(Context context) {
super(context);
mContext = context;
init();
}
public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
}
public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
init();
}
private void init(){
mLayoutManager = new WrapperLinearLayout(mContext,LinearLayoutManager.VERTICAL,false);
this.setLayoutManager(mLayoutManager);
this.setItemAnimator(new DefaultItemAnimator());
this.setHasFixedSize(true);
}
@Override
public void onScrolled(int dx, int dy) {
super.onScrolled(dx, dy);
if(dy > 0) //check for scroll down
{
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (loading)
{
if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount)
{
loading = false;
Log.v("...", "Call Load More !");
if(onLoadMoreListener != null){
onLoadMoreListener.onLoadMore();
}
//Do pagination.. i.e. fetch new data
}
}
}
}
@Override
public void onScrollStateChanged(int state) {
super.onScrollStateChanged(state);
}
public void onLoadMoreCompleted(){
loading = true;
}
public void setMoreLoading(boolean moreLoading){
loading = moreLoading;
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
}
WrapperLinearLayout
public class WrapperLinearLayout extends LinearLayoutManager
{
public WrapperLinearLayout(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
Log.e("probe", "meet a IOOBE in RecyclerView");
}
}
}
//Add it in xml like
<your.package.LoadMoreRecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</your.package.LoadMoreRecyclerView>
OnCreate or onViewCreated
mLoadMoreRecyclerView = (LoadMoreRecyclerView) view.findViewById(R.id.recycler_view);
mLoadMoreRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore() {
callYourService(StartIndex);
}
});
callYourService
private void callYourService(){
//callyour Service and get response in any List
List<AnyModelClass> newDataFromServer = getDataFromServerService();
//Enable Load More
mLoadMoreRecyclerView.onLoadMoreCompleted();
if(newDataFromServer != null && newDataFromServer.size() > 0){
StartIndex += newDataFromServer.size();
if (newDataFromServer.size() < Integer.valueOf(MAX_ROWS)) {
//StopLoading..
mLoadMoreRecyclerView.setMoreLoading(false);
}
}
else{
mLoadMoreRecyclerView.setMoreLoading(false);
mAdapter.notifyDataSetChanged();
}
}
If you have a valid integer value and your requirement is to compare values, you can simply go ahead with the comparison as seen below.
Sub t()
Dim i As Integer
Dim s As String
' pass
i = 65
s = "65"
If i = s Then
MsgBox i
End If
' fail - Type Mismatch
i = 65
s = "A"
If i = s Then
MsgBox i
End If
End Sub
As a general rule, you can use Database_Default collation so you don't need to figure out which one to use. However, I strongly suggest reading Simons Liew's excellent article Understanding the COLLATE DATABASE_DEFAULT clause in SQL Server
SELECT *
FROM [FAEB].[dbo].[ExportaComisiones] AS f
JOIN [zCredifiel].[dbo].[optPerson] AS p
ON (p.vTreasuryId = f.RFC) COLLATE Database_Default
New Cpanel Settings on a Godaddy
From Cpanel go to:
Increase post max size and upload max file size, save and your done.
Since in Javascript a string is a char array, you can access the last character by the length of the string.
var lastChar = myString[myString.length -1];
JSDoc 3 allows you to annotate your functions with the @access private
(previously the @private
tag) which is also useful for broadcasting your intent to other developers - http://usejsdoc.org/tags-access.html
the best way is using of nmap
tool in terminal.
nmap is an useful tool that analyse an up system, using it's IP Address
, then show all actived network services
.
open terminal
and use of this example :
~$ nmap 192.168.1.3/24
Starting Nmap 5.21 ( http://nmap.org ) at 2016-05-16 22:49 IRDT
Nmap scan report for 192.168.1.3
Host is up (0.00020s latency).
Not shown: 994 closed ports
PORT STATE SERVICE
22/tcp open ssh
23/tcp open telnet
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-term-serv
3689/tcp open rendezvous
This is cleaner and will put in a csv.
Import-Module ActiveDirectory
$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)
$Table = @()
$Record = [ordered]@{
"Group Name" = ""
"Name" = ""
"Username" = ""
}
Foreach ($Group in $Groups)
{
$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname
foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation
None of the answers so far explains how to download the various variants of that font so that you can serve them from your own website (WWW server).
While this might seem like a minor issue from the technical perspective, it is a big issue from the legal perspective, at least if you intend to present your pages to any EU citizen (or even, if you do that by accident). This is even true for companies which reside in the US (or any country outside the EU).
If anybody is interested why this is, I'll update this answer and give some more details here, but at the moment, I don't want to waste too much space off-topic.
Having said this:
I've downloaded all versions (regular, outlined, rounded, sharp, two-tone) of that font following two very easy steps (it was @Aj334's answer to his own question which put me on the right track) (example: "outlined" variant):
Get the CSS from the Google CDN by directly letting your browser fetch the CSS URL, i.e. copy the following URL into your browser's location bar:
https://fonts.googleapis.com/css?family=Material+Icons+Outlined
This will return a page which looks like this (at least in Firefox 70.0.1 at the time of writing this):
/* fallback */
@font-face {
font-family: 'Material Icons Outlined';
font-style: normal;
font-weight: 400;
src: url(https://fonts.gstatic.com/s/materialiconsoutlined/v14/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUce.woff2) format('woff2');
}
.material-icons-outlined {
font-family: 'Material Icons Outlined';
font-weight: normal;
font-style: normal;
font-size: 24px;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-block;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
-moz-font-feature-settings: 'liga';
-moz-osx-font-smoothing: grayscale;
}
Find the line starting with src:
in the above code, and let your browser fetch the URL contained in that line, i.e. copy the following URL into your browser's location bar:
https://fonts.gstatic.com/s/materialiconsoutlined/v14/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUce.woff2
Now the browser will download that .woff2
file and offer to save it locally (at least, Firefox did).
Two final remarks:
Of course, you can download the other variants of that font using the same method. In the first step, just replace the character sequence Outlined
in the URL by the character sequences Round
(yes, really, although here it's called "Rounded" in the left navigation menu), Sharp
or Two+Tone
, respectively. The result page will look nearly the same each time, but the URL in the src:
line of course is different for each variant.
Finally, in step 1, you even can use that URL:
https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp
This will return the CSS for all variants in one page, which then contains five src:
lines, each one with another URL designating where the respective font is located.
I have the same probblem, in version spring boot v1.3.x what i did is upgrade spring boot to version 1.5.7.RELEASE. Then the probblem gone.
document.getElementsByClassName('drill_cursor')[0]
.addEventListener('click', function (event) {
// do something
});
$(".drill_cursor").click(function(){
//do something
});
Don't delete it: for just one commit git cherry-pick
is enough.
But if you had several commits on the wrong branch, that is where git rebase --onto
shines:
Suppose you have this:
x--x--x--x <-- master
\
-y--y--m--m <- y branch, with commits which should have been on master
, then you can mark master
and move it where you would want to be:
git checkout master
git branch tmp
git checkout y
git branch -f master
x--x--x--x <-- tmp
\
-y--y--m--m <- y branch, master branch
, reset y branch where it should have been:
git checkout y
git reset --hard HEAD~2 # ~1 in your case,
# or ~n, n = number of commits to cancel
x--x--x--x <-- tmp
\
-y--y--m--m <- master branch
^
|
-- y branch
, and finally move your commits (reapply them, making actually new commits)
git rebase --onto tmp y master
git branch -D tmp
x--x--x--x--m'--m' <-- master
\
-y--y <- y branch
Regexes can also limit the number of characters.
r = re.compile("^[a-z]{1,15}$")
gives you a regex that only matches if the input is entirely lowercase ASCII letters and 1 to 15 characters long.
As nextXXX()
methods don't read newline
, except nextLine()
. We can skip the newline
after reading any non-string
value (int
in this case) by using scanner.skip()
as below:
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(x);
double y = sc.nextDouble();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(y);
char z = sc.next().charAt(0);
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(z);
String hello = sc.nextLine();
System.out.println(hello);
float tt = sc.nextFloat();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(tt);
Update: capability appears to have been removed by Apple on or around iOS 4
Just to expand on an earlier answer, something like this does it for me:
NSString *num = [[NSUserDefaults standardUserDefaults] stringForKey:@"SBFormattedPhoneNumber"];
Note: This retrieves the "Phone number" that was entered during the iPhone's iTunes activation and can be null or an incorrect value. It's NOT read from the SIM card.
At least that does in 2.1. There are a couple of other interesting keys in NSUserDefaults that may also not last. (This is in my app which uses a UIWebView)
WebKitJavaScriptCanOpenWindowsAutomatically
NSInterfaceStyle
TVOutStatus
WebKitDeveloperExtrasEnabledPreferenceKey
and so on.
Not sure what, if anything, the others do.
I think Amith Koujalgi is correct but also, in cases where the webservice responses are in JSON then it might be more useful to see the results in a clean JSON format instead of a very long string. Just add | grep }| python -mjson.tool to the end of curl commands here is two examples:
GET approach with JSON result
curl -i -H "Accept: application/json" http://someHostName/someEndpoint | grep }| python -mjson.tool
POST approach with JSON result
curl -X POST -H "Accept: Application/json" -H "Content-Type: application/json" http://someHostName/someEndpoint -d '{"id":"IDVALUE","name":"Mike"}' | grep }| python -mjson.tool
urls.py:
#...
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),
views.py:
from django.shortcuts import redirect
from .models import Element
def element_info(request):
# ...
element = Element.object.get(pk=1)
return redirect('element_update', pk=element.id)
def element_update(request, pk)
# ...
I have the same problem here, then I reinstalled mysql
and it worked.
sudo apt-get install mysql-server mysql-common mysql-client
I posted a solution using IBInspectable
, so you can change the max length value both in interface builder or programmatically. Check it out here
I tried all the solutions above and in addition, those in related answers as well. Solutions including but not limited to passing the blob manually to a HTMLInputElement's file property, calling all the readAs* methods on FileReader, using a File instance as second argument for a FormData.append call, trying to get the blob data as a string by getting the values at URL.createObjectURL(myBlob) which turned out nasty and crashed my machine.
Now, if you happen to attempt those or more and still find you're unable to upload your blob, it could mean the problem is server-side. In my case, my blob exceeded the http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize and post_max_size limit in PHP.INI so the file was leaving the front end form but getting rejected by the server. You could either increase this value directly in PHP.INI or via .htaccess
Access the field with array notation to avoid strict type checking on single field:
data['propertyName']; //will work even if data has not declared propertyName
Alternative way is (un)cast the variable for single access:
(<any>data).propertyName;//access propertyName like if data has no type
The first is shorter, the second is more explicit about type (un)casting
You can also totally disable type checking on all variable fields:
let untypedVariable:any= <any>{}; //disable type checking while declaring the variable
untypedVariable.propertyName = anyValue; //any field in untypedVariable is assignable and readable without type checking
Note: This would be more dangerous than avoid type checking just for a single field access, since all consecutive accesses on all fields are untyped
hierynomus/sshj has a complete implementation of SFTP version 3 (what OpenSSH implements)
Example code from SFTPUpload.java
package net.schmizz.sshj.examples;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.xfer.FileSystemFile;
import java.io.File;
import java.io.IOException;
/** This example demonstrates uploading of a file over SFTP to the SSH server. */
public class SFTPUpload {
public static void main(String[] args)
throws IOException {
final SSHClient ssh = new SSHClient();
ssh.loadKnownHosts();
ssh.connect("localhost");
try {
ssh.authPublickey(System.getProperty("user.name"));
final String src = System.getProperty("user.home") + File.separator + "test_file";
final SFTPClient sftp = ssh.newSFTPClient();
try {
sftp.put(new FileSystemFile(src), "/tmp");
} finally {
sftp.close();
}
} finally {
ssh.disconnect();
}
}
}
A few ways:
-- Do the comparison, OR'd with a check on the @Country=0 case
WHERE (a.Country = @Country OR @Country = 0)
-- compare the Country field to itself
WHERE a.Country = CASE WHEN @Country > 0 THEN @Country ELSE a.Country END
Or, use a dynamically generated statement and only add in the Country condition if appropriate. This should be most efficient in the sense that you only execute a query with the conditions that actually need to apply and can result in a better execution plan if supporting indices are in place. You would need to use parameterised SQL to prevent against SQL injection.
Apple has simplified our building process, so you don't need to click on the same checkbox every time. You can streamline your iTC flow by compiling this flag into the app.
This is still the case as of 2019.
The difference between npm install and npm update handling of package versions specified in package.json:
{
"name": "my-project",
"version": "1.0", // install update
"dependencies": { // ------------------
"already-installed-versionless-module": "*", // ignores "1.0" -> "1.1"
"already-installed-semver-module": "^1.4.3" // ignores "1.4.3" -> "1.5.2"
"already-installed-versioned-module": "3.4.1" // ignores ignores
"not-yet-installed-versionless-module": "*", // installs installs
"not-yet-installed-semver-module": "^4.2.1" // installs installs
"not-yet-installed-versioned-module": "2.7.8" // installs installs
}
}
Summary: The only big difference is that an already installed module with fuzzy versioning ...
npm install
npm update
Additionally: install
and update
by default handle devDependencies differently
npm install
will install/update devDependencies unless --production
flag is addednpm update
will ignore devDependencies unless --dev
flag is addedWhy use npm install
at all?
Because npm install
does more when you look besides handling your dependencies in package.json
.
As you can see in npm install you can ...
PATH
) using npm install -g <name>
--force
VBA stands for Visual Basic For Applications and its a Visual Basic implementation intended to be used in the Office Suite.
The difference between them is that VBA is embedded inside Office documents (its an Office feature). VB is the ide/language for developing applications.
In your example there is no big difference between str -> str
and Function.identity()
since internally it is simply t->t
.
But sometimes we can't use Function.identity
because we can't use a Function
. Take a look here:
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
this will compile fine
int[] arrayOK = list.stream().mapToInt(i -> i).toArray();
but if you try to compile
int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();
you will get compilation error since mapToInt
expects ToIntFunction
, which is not related to Function
. Also ToIntFunction
doesn't have identity()
method.
Apply the color to the li
and set the span
(or other child element) color to whatever color the text should be.
ul
{
list-style-type: square;
}
ul > li
{
color: green;
}
ul > li > span
{
color: black;
}
One approach would be to just use the ModelState
:
ModelState.AddModelError("", "Error in cloud - GetPLUInfo" + ex.Message);
and then on the view do something like this:
@Html.ValidationSummary()
where you want the errors to display. If there are no errors, it won't display, but if there are you'll get a section that lists all the errors.
def month_sub(year, month, sub_month):
result_month = 0
result_year = 0
if month > (sub_month % 12):
result_month = month - (sub_month % 12)
result_year = year - (sub_month / 12)
else:
result_month = 12 - (sub_month % 12) + month
result_year = year - (sub_month / 12 + 1)
return (result_year, result_month)
>>> month_sub(2015, 7, 1)
(2015, 6)
>>> month_sub(2015, 7, -1)
(2015, 8)
>>> month_sub(2015, 7, 13)
(2014, 6)
>>> month_sub(2015, 7, -14)
(2016, 9)
You can probably just use the true
command:
if [ "$a" -ge 10 ]; then
true
elif [ "$a" -le 5 ]; then
echo "1"
else
echo "2"
fi
An alternative, in your example case (but not necessarily everywhere) is to re-order your if/else:
if [ "$a" -le 5 ]; then
echo "1"
elif [ "$a" -lt 10 ]; then
echo "2"
fi
If you are using curl versions curl-7.19.7-46.el6.x86_64 or older. Please provide an option as -k1 (small K1).
php://input
can give you the raw bytes of the data. This is useful if the POSTed data is a JSON encoded structure, which is often the case for an AJAX POST request.
Here's a function to do just that:
/**
* Returns the JSON encoded POST data, if any, as an object.
*
* @return Object|null
*/
private function retrieveJsonPostData()
{
// get the raw POST data
$rawData = file_get_contents("php://input");
// this returns null if not valid json
return json_decode($rawData);
}
The $_POST
array is more useful when you're handling key-value data from a form, submitted by a traditional POST. This only works if the POSTed data is in a recognised format, usually application/x-www-form-urlencoded
(see http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4 for details).
I added a "Height" to my ListBox and it added the scrollbar nicely.
I had the similar problem and nothing was working out but then I Followed below Steps and It worked for me. when I ran cmd as administrator it worked fine for me.
First run the Command Prompt as administrator ans.
Create the new project.
If it still doesn't create the project, remove the folder and all it's files, and then run ng new <project name>
followed by ng serve
.
If nothing works just uninstall node and every other file related to it and follow the steps above
You can revert only one file to a specified revision.
First you can check on which commits the file was changed.
git log path/to/file.txt
Then you can checkout the file with the revision number.
git checkout 3cdc61015724f9965575ba954c8cd4232c8b42e4 /path/to/file.txt
After that you can commit and push it again.
StringBuilder b = new StringBuilder();
Scanner s = new Scanner(System.in);
String n = s.nextLine();
for(int i = 0; i < n.length(); i++) {
char c = n.charAt(i);
if(Character.isLowerCase(c) == true) {
b.append(String.valueOf(c).toUpperCase());
}
else {
b.append(String.valueOf(c).toLowerCase());
}
}
System.out.println(b);
Improving upon David Lemon's answer.
This converts form data to JSON and allows you to set the form from a data object.
const main = () => {_x000D_
const form = document.forms['info'];_x000D_
const data = {_x000D_
"user_name" : "John",_x000D_
"user_email" : "[email protected]",_x000D_
"user_created" : "2020-03-24",_x000D_
"user_age" : 42,_x000D_
"user_subscribed" : true,_x000D_
"user_interests" : "sports",_x000D_
"user_message" : "Hello My Friend"_x000D_
};_x000D_
_x000D_
populateForm(form, data);_x000D_
updateJsonView(form);_x000D_
form.addEventListener('change', (e) => updateJsonView(form));_x000D_
}_x000D_
_x000D_
const getFieldValue = (field, opts) => {_x000D_
let type = field.getAttribute('type');_x000D_
if (type) {_x000D_
switch (type) {_x000D_
case 'checkbox':_x000D_
return field.checked;_x000D_
case 'number':_x000D_
return field.value.includes('.')_x000D_
? parseFloat(field.value)_x000D_
: parseInt(field.value, 10);_x000D_
}_x000D_
}_x000D_
if (opts && opts[field.name] && opts[field.name].type) {_x000D_
switch (opts[field.name].type) {_x000D_
case 'int':_x000D_
return parseInt(field.value, 10);_x000D_
case 'float':_x000D_
return parseFloat(field.value);_x000D_
}_x000D_
}_x000D_
return field.value;_x000D_
}_x000D_
_x000D_
const setFieldValue = (field, value) => {_x000D_
let type = field.getAttribute('type');_x000D_
if (type) {_x000D_
switch (type) {_x000D_
case 'checkbox':_x000D_
field.checked = value;_x000D_
break;_x000D_
default:_x000D_
field.value = value;_x000D_
break;_x000D_
}_x000D_
} else {_x000D_
field.value = value;_x000D_
}_x000D_
}_x000D_
_x000D_
const extractFormData = (form, opts) => {_x000D_
return Array.from(form.elements).reduce((data, element) => {_x000D_
return Object.assign(data, { [element.name] : getFieldValue(element, opts) });_x000D_
}, {});_x000D_
};_x000D_
_x000D_
const populateForm = (form, data) => {_x000D_
return Array.from(form.elements).forEach((element) => {_x000D_
setFieldValue(element, data[element.name]);_x000D_
});_x000D_
};_x000D_
_x000D_
const updateJsonView = (form) => {_x000D_
let fieldOptions = {};_x000D_
let formData = extractFormData(form, fieldOptions);_x000D_
let serializedData = JSON.stringify(formData, null, 2);_x000D_
document.querySelector('.json-view').textContent = serializedData;_x000D_
};_x000D_
_x000D_
main();
_x000D_
.form-field {_x000D_
margin-bottom: 0.5em;_x000D_
}_x000D_
_x000D_
.form-field label {_x000D_
display: inline-block;_x000D_
font-weight: bold;_x000D_
width: 7em;_x000D_
vertical-align: top;_x000D_
}_x000D_
_x000D_
.json-view {_x000D_
position: absolute;_x000D_
top: 0.667em;_x000D_
right: 0.667em;_x000D_
border: thin solid grey;_x000D_
padding: 0.5em;_x000D_
white-space: pre;_x000D_
font-family: monospace;_x000D_
overflow: scroll-y;_x000D_
max-height: 100%;_x000D_
}
_x000D_
<form name="info" action="/my-handling-form-page" method="post">_x000D_
<div class="form-field">_x000D_
<label for="name">Name:</label>_x000D_
<input type="text" id="name" name="user_name">_x000D_
</div>_x000D_
<div class="form-field">_x000D_
<label for="mail">E-mail:</label>_x000D_
<input type="email" id="mail" name="user_email">_x000D_
</div>_x000D_
<div class="form-field">_x000D_
<label for="created">Date of Birth:</label>_x000D_
<input type="date" id="created" name="user_created">_x000D_
</div>_x000D_
<div class="form-field">_x000D_
<label for="age">Age:</label>_x000D_
<input type="number" id="age" name="user_age">_x000D_
</div>_x000D_
<div class="form-field">_x000D_
<label for="subscribe">Subscribe:</label>_x000D_
<input type="checkbox" id="subscribe" name="user_subscribed">_x000D_
</div>_x000D_
<div class="form-field">_x000D_
<label for="interests">Interest:</label>_x000D_
<select required="" id="interests" name="user_interests">_x000D_
<option value="" selected="selected">- None -</option>_x000D_
<option value="drums">Drums</option>_x000D_
<option value="js">Javascript</option>_x000D_
<option value="sports">Sports</option>_x000D_
<option value="trekking">Trekking</option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="form-field">_x000D_
<label for="msg">Message:</label>_x000D_
<textarea id="msg" name="user_message"></textarea>_x000D_
</div>_x000D_
</form>_x000D_
<div class="json-view"></div>
_x000D_
For Intellij IDEA type sout
and press Tab.
For Eclipse type syso
and press Ctrl+Space.
Calculate the total size of the database at the end:
(SELECT
table_name AS `Table`,
round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB`
FROM information_schema.TABLES
WHERE table_schema = "$DB_NAME"
)
UNION ALL
(SELECT
'TOTAL:',
SUM(round(((data_length + index_length) / 1024 / 1024), 2) )
FROM information_schema.TABLES
WHERE table_schema = "$DB_NAME"
)