Instead of using a Label
use a text input:
<script type="text/javascript">
onChange = function(ctrl) {
var txt = document.getElementById("<%= txtResult.ClientID %>");
if (txt){
txt.value = ctrl.value;
}
}
</script>
<asp:TextBox ID="txtTest" runat="server" onchange="onChange(this);" />
<!-- pseudo label that will survive postback -->
<input type="text" id="txtResult" runat="server" readonly="readonly" tabindex="-1000" style="border:0px;background-color:transparent;" />
<asp:Button ID="btnTest" runat="server" Text="Test" />
By default Sharepoint does not allow server-side code to be executed in ASPX files. See this for how to resolve that.
However, I would raise that having a code-behind is not necessarily difficult to deploy in Sharepoint (we do it extensively) - just compile your code-behind classes into an assembly and deploy it using a solution.
If still no, you can include all the code you'd normally place in a codebehind like so:
<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
//hello, world!
}
</script>
In my case, when I created the web form, it was named as WebForm1.aspx and respective names (WebForm1). Letter, I renamed that to something else. I renamed manually at almost all the places, but one place in designer file was still showing it as 'WebForm1'.
I changed that too and got rid of this error.
If you are trying to access an html element: this is an HTML Anchor...
My nav bar has items that are not list items (<li>
) but rather html anchors (<a>
)
See below: (This is the site master)
<nav class="mdl-navigation">
<a class="mdl-navigation__link" href="" runat="server" id="liHome">Home</a>
<a class="mdl-navigation__link" href="" runat="server" id="liDashboard">Dashboard</a>
</nav>
Now in your code behind for another page, for mine, it's the login page...
On PageLoad() define this:
HtmlAnchor lblMasterStatus = (HtmlAnchor)Master.FindControl("liHome");
lblMasterStatus.Visible =false;
HtmlAnchor lblMasterStatus1 = (HtmlAnchor)Master.FindControl("liDashboard");
lblMasterStatus1.Visible = false;
Now we have accessed the site masters controls, and have made them invisible on the login page.
Use asp:image
<asp:Image id="Image1" runat="server"
AlternateText="Image text"
ImageAlign="left"
ImageUrl="images/image1.jpg"/>
and codebehind to change image url
Image1.ImageUrl = "/MyProject;component/Images/down.png";
You can use the Page.ClientScript.RegisterStartupScript method.
Not exactly direct answer, but strongly related:
In case the resources are in a different file - for example ResourceDictionary.xaml
You can simply add x:Class
to it:
<ResourceDictionary x:Class="Namespace.NewClassName"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<ds:MyCollection x:Key="myKey" x:Name="myName" />
</ResourceDictionary>
And then use it in code behind:
var res = new Namespace.NewClassName();
var col = res["myKey"];
You can use a Web Method and Ajax:
<script type="text/javascript"> //Default.aspx
function DeleteKartItems() {
$.ajax({
type: "POST",
url: 'Default.aspx/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>
[WebMethod] //Default.aspx.cs
public static void DeleteItem()
{
//Your Logic
}
If you want to add attributes, including the class, you need to set runat="server"
on the tag.
<div id="classMe" runat="server"></div>
Then in the code-behind:
classMe.Attributes.Add("class", "some-class")
not really. Server side code is happening on the server--- you can use javascript to display something to the user on the client side, but it obviously will only execute on the client side. This is the nature of a client server web technology. You're basically disconnected from the server when you get your response.
You can get it with .outerHeight()
.
Sometimes, it will return 0
. For the best results, you can call it in your div
's ready event.
To be safe, you should not set the height of the div
to x
. You can keep its height auto
to get content populated properly with the correct height.
$('#x').ready( function(){
// alerts the height in pixels
alert($('#x').outerHeight());
})
You can find a detailed post here.
You need change instantiateItem's mFragments element getItemPosition.
if (mFragments.size() > position) {
Fragment f = mFragments.get(position);
if (f != null) {
int newPosition = getItemPosition(f);
if (newPosition == POSITION_UNCHANGED) {
return f;
} else if (newPosition == POSITION_NONE) {
mFragments.set(position, null);
} else {
mFragments.set(newPosition, f);
}
}
}
Based AndroidX FragmentStatePagerAdapter.java, because mFragments
's elements position do not change when calling notifyDataSetChanged().
You can run this project to confirm how to work. https://github.com/cuichanghao/infivt
Unless you're trying to upload the file using ajax, just submit the form to /upload/image
.
<form enctype="multipart/form-data" action="/upload/image" method="post">
<input id="image-file" type="file" />
</form>
If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:
using jQuery:
$('form').submit(function(){
$(':submit', this).click(function() {
return false;
});
});
In C, it is good style because you can change the type to something besides an enum.
typedef enum e_TokenType
{
blah1 = 0x00000000,
blah2 = 0X01000000,
blah3 = 0X02000000
} TokenType;
foo(enum e_TokenType token); /* this can only be passed as an enum */
foo(TokenType token); /* TokenType can be defined to something else later
without changing this declaration */
In C++ you can define the enum so that it will compile as C++ or C.
The old syntax, with just listing the tables, and using the WHERE
clause to specify the join criteria, is being deprecated in most modern databases.
It's not just for show, the old syntax has the possibility of being ambiguous when you use both INNER and OUTER joins in the same query.
Let me give you an example.
Let's suppose you have 3 tables in your system:
Company
Department
Employee
Each table contain numerous rows, linked together. You got multiple companies, and each company can have multiple departments, and each department can have multiple employees.
Ok, so now you want to do the following:
List all the companies, and include all their departments, and all their employees. Note that some companies don't have any departments yet, but make sure you include them as well. Make sure you only retrieve departments that have employees, but always list all companies.
So you do this:
SELECT * -- for simplicity
FROM Company, Department, Employee
WHERE Company.ID *= Department.CompanyID
AND Department.ID = Employee.DepartmentID
Note that the last one there is an inner join, in order to fulfill the criteria that you only want departments with people.
Ok, so what happens now. Well, the problem is, it depends on the database engine, the query optimizer, indexes, and table statistics. Let me explain.
If the query optimizer determines that the way to do this is to first take a company, then find the departments, and then do an inner join with employees, you're not going to get any companies that don't have departments.
The reason for this is that the WHERE
clause determines which rows end up in the final result, not individual parts of the rows.
And in this case, due to the left join, the Department.ID column will be NULL, and thus when it comes to the INNER JOIN to Employee, there's no way to fulfill that constraint for the Employee row, and so it won't appear.
On the other hand, if the query optimizer decides to tackle the department-employee join first, and then do a left join with the companies, you will see them.
So the old syntax is ambiguous. There's no way to specify what you want, without dealing with query hints, and some databases have no way at all.
Enter the new syntax, with this you can choose.
For instance, if you want all companies, as the problem description stated, this is what you would write:
SELECT *
FROM Company
LEFT JOIN (
Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID
) ON Company.ID = Department.CompanyID
Here you specify that you want the department-employee join to be done as one join, and then left join the results of that with the companies.
Additionally, let's say you only want departments that contains the letter X in their name. Again, with old style joins, you risk losing the company as well, if it doesn't have any departments with an X in its name, but with the new syntax, you can do this:
SELECT *
FROM Company
LEFT JOIN (
Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID
) ON Company.ID = Department.CompanyID AND Department.Name LIKE '%X%'
This extra clause is used for the joining, but is not a filter for the entire row. So the row might appear with company information, but might have NULLs in all the department and employee columns for that row, because there is no department with an X in its name for that company. This is hard with the old syntax.
This is why, amongst other vendors, Microsoft has deprecated the old outer join syntax, but not the old inner join syntax, since SQL Server 2005 and upwards. The only way to talk to a database running on Microsoft SQL Server 2005 or 2008, using the old style outer join syntax, is to set that database in 8.0 compatibility mode (aka SQL Server 2000).
Additionally, the old way, by throwing a bunch of tables at the query optimizer, with a bunch of WHERE clauses, was akin to saying "here you are, do the best you can". With the new syntax, the query optimizer has less work to do in order to figure out what parts goes together.
So there you have it.
LEFT and INNER JOIN is the wave of the future.
Here i am posting the answer just for reference which may become useful.
<!DOCTYPE html>
<html>
<head>
<script>
function show()
{
var InvForm = document.forms.form;
var SelBranchVal = "";
var x = 0;
for (x=0;x<InvForm.kb.length;x++)
{
if(InvForm.kb[x].selected)
{
//alert(InvForm.kb[x].value);
SelBranchVal = InvForm.kb[x].value + "," + SelBranchVal ;
}
}
alert(SelBranchVal);
}
</script>
</head>
<body>
<form name="form">
<select name="kb" id="kb" onclick="show();" multiple>
<option value="India">India</option>
<option selected="selected" value="US">US</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
</select>
<!--input type="submit" name="cmdShow" value="Customize Fields"
onclick="show();" id="cmdShow" /-->
</form>
</body>
</html>
Working off of Matt's solution, I used the following Compass/SCSS implementation.
@for $i from 1 through 20 {
li:first-child:nth-last-child( #{$i} ),
li:first-child:nth-last-child( #{$i} ) ~ li {
width: calc(100% / #{$i} - 10px);
}
}
This allows you to quickly expand the number of items.
I think it's better to point out that using Make (recursive or not) is something that usually you may want to avoid, because compared to today tools, it's difficult to learn, maintain and scale.
It's a wonderful tool but it's direct use should be considered obsolete in 2010+.
Unless, of course, you're working in a special environment i.e. with a legacy project etc.
Use an IDE, CMake or, if you're hard cored, the Autotools.
(edited due to downvotes, ty Honza for pointing out)
Use Java 8's removeIf(),
To remove safely,
letters.removeIf(x -> !x.equals("A"));
Try the load() function.
$('#content').load("http://vnexpress.net");
Please not that for this to work, the URL to be loaded must either be on the same domain as the page that's calling it, or enable cross-origin HTTP requests ("Cross-Origin Resource Sharing", short CORS) on the server. This involves sending an additional HTTP header, in its most basic form:
Access-Control-Allow-Origin:*
to allow requests from everywhere.
i made a method that merge cells and put border.
protected void setMerge(Sheet sheet, int numRow, int untilRow, int numCol, int untilCol, boolean border) {
CellRangeAddress cellMerge = new CellRangeAddress(numRow, untilRow, numCol, untilCol);
sheet.addMergedRegion(cellMerge);
if (border) {
setBordersToMergedCells(sheet, cellMerge);
}
}
protected void setBordersToMergedCells(Sheet sheet, CellRangeAddress rangeAddress) {
RegionUtil.setBorderTop(BorderStyle.MEDIUM, rangeAddress, sheet);
RegionUtil.setBorderLeft(BorderStyle.MEDIUM, rangeAddress, sheet);
RegionUtil.setBorderRight(BorderStyle.MEDIUM, rangeAddress, sheet);
RegionUtil.setBorderBottom(BorderStyle.MEDIUM, rangeAddress, sheet);
}
You can prevent future connections:
REVOKE CONNECT ON DATABASE thedb FROM public;
(and possibly other users/roles; see \l+
in psql
)
You can then terminate all connections to this db except your own:
SELECT pid, pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = current_database() AND pid <> pg_backend_pid();
On older versions pid
was called procpid
so you'll have to deal with that.
Since you've revoked CONNECT
rights, whatever was trying to auto-connect should no longer be able to do so.
You'll now be able to drop the DB.
This won't work if you're using superuser connections for normal operations, but if you're doing that you need to fix that problem first.
After you're done dropping the database, if you create the database again, you can execute below command to restore the access
GRANT CONNECT ON DATABASE thedb TO public;
For me, world wide web publishing-service was using port 80. I killed this by running the following command on cmd:
net stop http
After that, XAMPP ran Apache without any problems.
sudo ./scriptname
sudo bash will basically switch you over to running a shell as root, although it's probably best to stay as su as little as possible.
Start GDB on your project.
Go to project directory, where you've already compiled the project executable. Issue the command gdb and the name of the executable as below:
gdb projectExecutablename
This starts up gdb, prints the following: GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1 Copyright (C) 2016 Free Software Foundation, Inc. ................................................. Type "apropos word" to search for commands related to "word"... Reading symbols from projectExecutablename...done. (gdb)
Before you start your program running, you want to set up your breakpoints. The break command allows you to do so. To set a breakpoint at the beginning of the function named main:
(gdb) b main
Once you've have the (gdb) prompt, the run command starts the executable running. If the program you are debugging requires any command-line arguments, you specify them to the run command. If you wanted to run my program on the "xfiles" file (which is in a folder "mulder" in the project directory), you'd do the following:
(gdb) r mulder/xfiles
Hope this helps.
Disclaimer: This solution is not mine, it is adapted from https://web.stanford.edu/class/cs107/guide_gdb.html This short guide to gdb was, most probably, developed at Stanford University.
Based on Kyle_the_hacker's -----> answer with my extras.
In terminal
List all locales
locale -a
Install all locales
sudo apt-get install -y locales locales-all
Compile main.cpp
$ g++ main.cpp
Run compiled program
$ ./a.out
Results
Zoë Saldaña played in La maldición del padre Cardona. ëèñ a? óóChloë
Zoë Saldaña played in La maldición del padre Cardona. ëèñ a? óóChloë
ZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ?O ÓÓCHLOË
ZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ?O ÓÓCHLOË
zoë saldaña played in la maldición del padre cardona. ëèñ a? óóchloë
zoë saldaña played in la maldición del padre cardona. ëèñ a? óóchloë
In cmd run VCVARS developer tools
"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"
Compile main.cpp
> cl /EHa main.cpp /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /std:c++17 /DYNAMICBASE "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib" "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib" "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib" /MTd
Compilador de optimización de C/C++ de Microsoft (R) versión 19.27.29111 para x64
(C) Microsoft Corporation. Todos los derechos reservados.
main.cpp
Microsoft (R) Incremental Linker Version 14.27.29111.0
Copyright (C) Microsoft Corporation. All rights reserved.
/out:main.exe
main.obj
kernel32.lib
user32.lib
gdi32.lib
winspool.lib
comdlg32.lib
advapi32.lib
shell32.lib
ole32.lib
oleaut32.lib
uuid.lib
odbc32.lib
odbccp32.lib
Run main.exe
>main.exe
Results
Zoë Saldaña played in La maldición del padre Cardona. ëèñ a? óóChloë
Zoë Saldaña played in La maldición del padre Cardona. ëèñ a? óóChloë
ZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ?O ÓÓCHLOË
ZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ?O ÓÓCHLOË
zoë saldaña played in la maldición del padre cardona. ëèñ a? óóchloë
zoë saldaña played in la maldición del padre cardona. ëèñ a? óóchloë
This code was only tested on Windows x64 and Ubuntu Linux x64.
/*
* Filename: c:\Users\x\Cpp\main.cpp
* Path: c:\Users\x\Cpp
* Filename: /home/x/Cpp/main.cpp
* Path: /home/x/Cpp
* Created Date: Saturday, October 17th 2020, 10:43:31 pm
* Author: Joma
*
* No Copyright 2020
*/
#include <iostream>
#include <set>
#include <string>
#include <locale>
// WINDOWS
#if (_WIN32)
#include <Windows.h>
#include <conio.h>
#define WINDOWS_PLATFORM 1
#define DLLCALL STDCALL
#define DLLIMPORT _declspec(dllimport)
#define DLLEXPORT _declspec(dllexport)
#define DLLPRIVATE
#define NOMINMAX
//EMSCRIPTEN
#elif defined(__EMSCRIPTEN__)
#include <emscripten/emscripten.h>
#include <emscripten/bind.h>
#include <unistd.h>
#include <termios.h>
#define EMSCRIPTEN_PLATFORM 1
#define DLLCALL
#define DLLIMPORT
#define DLLEXPORT __attribute__((visibility("default")))
#define DLLPRIVATE __attribute__((visibility("hidden")))
// LINUX - Ubuntu, Fedora, , Centos, Debian, RedHat
#elif (__LINUX__ || __gnu_linux__ || __linux__ || __linux || linux)
#define LINUX_PLATFORM 1
#include <unistd.h>
#include <termios.h>
#define DLLCALL CDECL
#define DLLIMPORT
#define DLLEXPORT __attribute__((visibility("default")))
#define DLLPRIVATE __attribute__((visibility("hidden")))
#define CoTaskMemAlloc(p) malloc(p)
#define CoTaskMemFree(p) free(p)
//ANDROID
#elif (__ANDROID__ || ANDROID)
#define ANDROID_PLATFORM 1
#define DLLCALL
#define DLLIMPORT
#define DLLEXPORT __attribute__((visibility("default")))
#define DLLPRIVATE __attribute__((visibility("hidden")))
//MACOS
#elif defined(__APPLE__)
#include <unistd.h>
#include <termios.h>
#define DLLCALL
#define DLLIMPORT
#define DLLEXPORT __attribute__((visibility("default")))
#define DLLPRIVATE __attribute__((visibility("hidden")))
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
#define IOS_SIMULATOR_PLATFORM 1
#elif TARGET_OS_IPHONE
#define IOS_PLATFORM 1
#elif TARGET_OS_MAC
#define MACOS_PLATFORM 1
#else
#endif
#endif
typedef std::string String;
typedef std::wstring WString;
#define EMPTY_STRING u8""s
#define EMPTY_WSTRING L""s
using namespace std::literals::string_literals;
class Strings
{
public:
static String WideStringToString(const WString& wstr)
{
if (wstr.empty())
{
return String();
}
size_t pos;
size_t begin = 0;
String ret;
#if WINDOWS_PLATFORM
int size;
pos = wstr.find(static_cast<wchar_t>(0), begin);
while (pos != WString::npos && begin < wstr.length())
{
WString segment = WString(&wstr[begin], pos - begin);
size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), NULL, 0, NULL, NULL);
String converted = String(size, 0);
WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), &converted[0], converted.size(), NULL, NULL);
ret.append(converted);
ret.append({ 0 });
begin = pos + 1;
pos = wstr.find(static_cast<wchar_t>(0), begin);
}
if (begin <= wstr.length())
{
WString segment = WString(&wstr[begin], wstr.length() - begin);
size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), NULL, 0, NULL, NULL);
String converted = String(size, 0);
WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), &converted[0], converted.size(), NULL, NULL);
ret.append(converted);
}
#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM
size_t size;
pos = wstr.find(static_cast<wchar_t>(0), begin);
while (pos != WString::npos && begin < wstr.length())
{
WString segment = WString(&wstr[begin], pos - begin);
size = wcstombs(nullptr, segment.c_str(), 0);
String converted = String(size, 0);
wcstombs(&converted[0], segment.c_str(), converted.size());
ret.append(converted);
ret.append({ 0 });
begin = pos + 1;
pos = wstr.find(static_cast<wchar_t>(0), begin);
}
if (begin <= wstr.length())
{
WString segment = WString(&wstr[begin], wstr.length() - begin);
size = wcstombs(nullptr, segment.c_str(), 0);
String converted = String(size, 0);
wcstombs(&converted[0], segment.c_str(), converted.size());
ret.append(converted);
}
#else
static_assert(false, "Unknown Platform");
#endif
return ret;
}
static WString StringToWideString(const String& str)
{
if (str.empty())
{
return WString();
}
size_t pos;
size_t begin = 0;
WString ret;
#ifdef WINDOWS_PLATFORM
int size = 0;
pos = str.find(static_cast<char>(0), begin);
while (pos != std::string::npos) {
std::string segment = std::string(&str[begin], pos - begin);
std::wstring converted = std::wstring(segment.size() + 1, 0);
size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, &segment[0], segment.size(), &converted[0], converted.length());
converted.resize(size);
ret.append(converted);
ret.append({ 0 });
begin = pos + 1;
pos = str.find(static_cast<char>(0), begin);
}
if (begin < str.length()) {
std::string segment = std::string(&str[begin], str.length() - begin);
std::wstring converted = std::wstring(segment.size() + 1, 0);
size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, segment.c_str(), segment.size(), &converted[0], converted.length());
converted.resize(size);
ret.append(converted);
}
#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM
size_t size;
pos = str.find(static_cast<char>(0), begin);
while (pos != String::npos)
{
String segment = String(&str[begin], pos - begin);
WString converted = WString(segment.size(), 0);
size = mbstowcs(&converted[0], &segment[0], converted.size());
converted.resize(size);
ret.append(converted);
ret.append({ 0 });
begin = pos + 1;
pos = str.find(static_cast<char>(0), begin);
}
if (begin < str.length())
{
String segment = String(&str[begin], str.length() - begin);
WString converted = WString(segment.size(), 0);
size = mbstowcs(&converted[0], &segment[0], converted.size());
converted.resize(size);
ret.append(converted);
}
#else
static_assert(false, "Unknown Platform");
#endif
return ret;
}
static WString ToUpper(const WString& data)
{
WString result = data;
auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());
f.toupper(&result[0], &result[0] + result.size());
return result;
}
static String ToUpper(const String& data)
{
return WideStringToString(ToUpper(StringToWideString(data)));
}
static WString ToLower(const WString& data)
{
WString result = data;
auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());
f.tolower(&result[0], &result[0] + result.size());
return result;
}
static String ToLower(const String& data)
{
return WideStringToString(ToLower(StringToWideString(data)));
}
};
enum class ConsoleTextStyle
{
DEFAULT = 0,
BOLD = 1,
FAINT = 2,
ITALIC = 3,
UNDERLINE = 4,
SLOW_BLINK = 5,
RAPID_BLINK = 6,
REVERSE = 7,
};
enum class ConsoleForeground
{
DEFAULT = 39,
BLACK = 30,
DARK_RED = 31,
DARK_GREEN = 32,
DARK_YELLOW = 33,
DARK_BLUE = 34,
DARK_MAGENTA = 35,
DARK_CYAN = 36,
GRAY = 37,
DARK_GRAY = 90,
RED = 91,
GREEN = 92,
YELLOW = 93,
BLUE = 94,
MAGENTA = 95,
CYAN = 96,
WHITE = 97
};
enum class ConsoleBackground
{
DEFAULT = 49,
BLACK = 40,
DARK_RED = 41,
DARK_GREEN = 42,
DARK_YELLOW = 43,
DARK_BLUE = 44,
DARK_MAGENTA = 45,
DARK_CYAN = 46,
GRAY = 47,
DARK_GRAY = 100,
RED = 101,
GREEN = 102,
YELLOW = 103,
BLUE = 104,
MAGENTA = 105,
CYAN = 106,
WHITE = 107
};
class Console
{
private:
static void EnableVirtualTermimalProcessing()
{
#if defined WINDOWS_PLATFORM
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD dwMode = 0;
GetConsoleMode(hOut, &dwMode);
if (!(dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING))
{
dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(hOut, dwMode);
}
#endif
}
static void ResetTerminalFormat()
{
std::cout << u8"\033[0m";
}
static void SetVirtualTerminalFormat(ConsoleForeground foreground, ConsoleBackground background, std::set<ConsoleTextStyle> styles)
{
String format = u8"\033[";
format.append(std::to_string(static_cast<int>(foreground)));
format.append(u8";");
format.append(std::to_string(static_cast<int>(background)));
if (styles.size() > 0)
{
for (auto it = styles.begin(); it != styles.end(); ++it)
{
format.append(u8";");
format.append(std::to_string(static_cast<int>(*it)));
}
}
format.append(u8"m");
std::cout << format;
}
public:
static void Clear()
{
#ifdef WINDOWS_PLATFORM
std::system(u8"cls");
#elif LINUX_PLATFORM || defined MACOS_PLATFORM
std::system(u8"clear");
#elif EMSCRIPTEN_PLATFORM
emscripten::val::global()["console"].call<void>(u8"clear");
#else
static_assert(false, "Unknown Platform");
#endif
}
static void Write(const String& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})
{
#ifndef EMSCRIPTEN_PLATFORM
EnableVirtualTermimalProcessing();
SetVirtualTerminalFormat(foreground, background, styles);
#endif
String str = s;
#ifdef WINDOWS_PLATFORM
WString unicode = Strings::StringToWideString(str);
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), unicode.c_str(), static_cast<DWORD>(unicode.length()), nullptr, nullptr);
#elif defined LINUX_PLATFORM || defined MACOS_PLATFORM || EMSCRIPTEN_PLATFORM
std::cout << str;
#else
static_assert(false, "Unknown Platform");
#endif
#ifndef EMSCRIPTEN_PLATFORM
ResetTerminalFormat();
#endif
}
static void WriteLine(const String& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})
{
Write(s, foreground, background, styles);
std::cout << std::endl;
}
static void Write(const WString& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})
{
#ifndef EMSCRIPTEN_PLATFORM
EnableVirtualTermimalProcessing();
SetVirtualTerminalFormat(foreground, background, styles);
#endif
WString str = s;
#ifdef WINDOWS_PLATFORM
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), str.c_str(), static_cast<DWORD>(str.length()), nullptr, nullptr);
#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM
std::cout << Strings::WideStringToString(str);
#else
static_assert(false, "Unknown Platform");
#endif
#ifndef EMSCRIPTEN_PLATFORM
ResetTerminalFormat();
#endif
}
static void WriteLine(const WString& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})
{
Write(s, foreground, background, styles);
std::cout << std::endl;
}
static void WriteLine()
{
std::cout << std::endl;
}
static void Pause()
{
char c;
do
{
c = getchar();
std::cout << "Press Key " << std::endl;
} while (c != 64);
std::cout << "KeyPressed" << std::endl;
}
static int PauseAny(bool printWhenPressed = false, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})
{
int ch;
#ifdef WINDOWS_PLATFORM
ch = _getch();
#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM
struct termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
#else
static_assert(false, "Unknown Platform");
#endif
if (printWhenPressed)
{
Console::Write(String(1, ch), foreground, background, styles);
}
return ch;
}
};
int main()
{
std::locale::global(std::locale(u8"en_US.UTF-8"));
String dataStr = u8"Zoë Saldaña played in La maldición del padre Cardona. ëèñ a? óóChloë";
WString dataWStr = L"Zoë Saldaña played in La maldición del padre Cardona. ëèñ a? óóChloë";
std::string locale = u8"";
//std::string locale = u8"de_DE.UTF-8";
//std::string locale = u8"en_US.UTF-8";
Console::WriteLine(dataStr);
Console::WriteLine(dataWStr);
dataStr = Strings::ToUpper(dataStr);
dataWStr = Strings::ToUpper(dataWStr);
Console::WriteLine(dataStr);
Console::WriteLine(dataWStr);
dataStr = Strings::ToLower(dataStr);
dataWStr = Strings::ToLower(dataWStr);
Console::WriteLine(dataStr);
Console::WriteLine(dataWStr);
Console::WriteLine(u8"Press any key to exit"s, ConsoleForeground::DARK_GRAY);
Console::PauseAny();
return 0;
}
It is better to use this syntax to replace all the commas in a case of a million 1,234,567
var string = "1,234,567";
string = string.replace(/[^\d\.\-]/g, "");
var number = parseFloat(string);
console.log(number)
The g
means to remove all commas.
Check the Jsfiddle demo here.
I guess you want to do this:
$total_rating_count = count($total_rating_count);
if ($total_rating_count > 0) // because you can't divide through zero
$avg = round($total_rating_points / $total_rating_count, 1);
You may try
$("#addRunner input").each(function(){ ... });
Inputs are no selectors, so you do not need the :
Haven't tested it with your code. Just a fast guess!
I don't have to many bulky code to give out just a little snippet solved the issue for me.
i have https://example.com/entitlements/index.php rather i want anyone that types it to get error on request event if you type https://example.com/entitlements/index you will still get error since there's this word "index" is contained there will always be an error thrown back though the content of index.php will still be displayed properly
cletus post on "https://stackoverflow.com/a/1055655/12192635" which solved it
Edit your .htaccess file with the below to redirect people visiting https://example.com/entitlements/index.php to 404 page
RewriteCond %{THE_REQUEST} \.php[\ /?].*HTTP/
RewriteRule ^.*$ - [R=404,L]
to redirect people visiting https://example.com/entitlements/index to 404 page
RewriteCond %{THE_REQUEST} \index[\ /?].*HTTP/
RewriteRule ^.*$ - [R=404,L]
Not withstanding we have already known that the above code works with already existing codes on stack see where i applied the code above just below the all codes at it end.
# The following will allow you to use URLs such as the following:
#
# example.com/anything
# example.com/anything/
#
# Which will actually serve files such as the following:
#
# example.com/anything.html
# example.com/anything.php
#
# But *only if they exist*, otherwise it will report the usual 404 error.
Options +FollowSymLinks
RewriteEngine On
# Remove trailing slashes.
# e.g. example.com/foo/ will redirect to example.com/foo
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R=permanent,QSA]
# Redirect to HTML if it exists.
# e.g. example.com/foo will display the contents of example.com/foo.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ $1.html [L,QSA]
# Redirect to PHP if it exists.
# e.g. example.com/foo will display the contents of example.com/foo.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php [L,QSA]
RewriteCond %{THE_REQUEST} \.php[\ /?].*HTTP/
RewriteRule ^.*$ - [R=404,L]
RewriteCond %{THE_REQUEST} \index[\ /?].*HTTP/
RewriteRule ^.*$ - [R=404,L]
First off, your trigger as you already see is going to update every record in the table. There is no filtering done to accomplish jus the rows changed.
Secondly, you're assuming that only one row changes in the batch which is incorrect as multiple rows could change.
The way to do this properly is to use the virtual inserted and deleted tables: http://msdn.microsoft.com/en-us/library/ms191300.aspx
In Win10 it might be helpful to download VirtualBox latest version.
It was the only thing that solved it for me. Hope it will save someone some time and trouble.
Qberticus's answer is good, but one useful detail is missing. If you are implementing these in a library replace:
xmlns:whatever="http://schemas.android.com/apk/res/org.example.mypackage"
with:
xmlns:whatever="http://schemas.android.com/apk/res-auto"
Otherwise the application that uses the library will have runtime errors.
I like this very simple definition: (source)
A loop invariant is a condition [among program variables] that is necessarily true immediately before and immediately after each iteration of a loop. (Note that this says nothing about its truth or falsity part way through an iteration.)
By itself, a loop invariant doesn't do much. However, given an appropriate invariant, it can be used to help prove the correctness of an algorithm. The simple example in CLRS probably has to do with sorting. For example, let your loop invariant be something like, at the start of the loop, the first i
entries of this array are sorted. If you can prove that this is indeed a loop invariant (i.e. that it holds before and after every loop iteration), you can use this to prove the correctness of a sorting algorithm: at the termination of the loop, the loop invariant is still satisfied, and the counter i
is the length of the array. Therefore, the first i
entries are sorted means the entire array is sorted.
An even simpler example: Loops Invariants, Correctness, and Program Derivation.
The way I understand a loop invariant is as a systematic, formal tool to reason about programs. We make a single statement that we focus on proving true, and we call it the loop invariant. This organizes our logic. While we can just as well argue informally about the correctness of some algorithm, using a loop invariant forces us to think very carefully and ensures our reasoning is airtight.
Most modern linkers include a verbose option that prints out to varying degrees;
For gcc and clang; you would typically add -v -Wl,--verbose
or -v -Wl,-v
to the command line. More details can be found here;
For MSVC, /VERBOSE
(in particular /VERBOSE:LIB
) is added to the link command line.
/VERBOSE
linker option.If table is without partition then code will be,
Insert into table table_name
select col_a,col_b,col_c from another_table(source table)
--here any condition can be applied such as limit, group by, order by etc...
If table is with partitions then code will be,
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;
insert into table table_name
partition(partition_col1
, paritition_col2
)
select col_a,col_b,col_c,partition_col1,partition_col2
from another_table(source table)
--here any condition can be applied such as limit, group by, order by etc...
Another method for cleaner argument passing would be splatting.
Define your parameters and values as a hashtable like this:
$params = @{ 'class' = 'Win32_BIOS';
'computername'='SERVER-R2';
'filter'='drivetype=3';
'credential'='Administrator' }
And then call your commandlet like this:
Get-WmiObject @params
Microsoft Docs: About Splatting
TechNet Magazine 2011: Windows PowerShell: Splatting
You're looking for delete
:
delete myhash['key2']
See the Core Javascript Guide
Most cases where you would need to pass by reference are where you need to return more than one value back to the caller. A "best practice" is to use multiple return values, which is much easier to do in Python than in languages like Java.
Here's a simple example:
def RectToPolar(x, y):
r = (x ** 2 + y ** 2) ** 0.5
theta = math.atan2(y, x)
return r, theta # return 2 things at once
r, theta = RectToPolar(3, 4) # assign 2 things at once
How can you get the tree-like view of commits in terminal?
git log --graph --oneline --all
is a good start.
You may get some strange letters. They are ASCII codes for colors and structure. To solve this problem add the following to your .bashrc
:
export LESS="-R"
such that you do not need use Tig's ASCII filter by
git log --graph --pretty=oneline --abbrev-commit | tig // Masi needed this
The article text-based graph from Git-ready contains other options:
git log --graph --pretty=oneline --abbrev-commit
Regarding the article you mention, I would go with Pod's answer: ad-hoc hand-made output.
Jakub Narebski mentions in the comments tig, a ncurses-based text-mode interface for git. See their releases.
It added a --graph
option back in 2007.
Try as
String s = "ABC[ This is to extract ]";
Pattern p = Pattern.compile(".*\\[ *(.*) *\\].*");
Matcher m = p.matcher(s);
m.find();
String text = m.group(1);
System.out.println(text);
Use this:
boolean success = EmailIntentBuilder.from(activity)
.to("[email protected]")
.cc("[email protected]")
.subject("Error report")
.body(buildErrorReport())
.start();
use build gradle :
compile 'de.cketti.mailto:email-intent-builder:1.0.0'
To do that you need to leverage the "Collections" feature of Postman. This link could help you: https://learning.getpostman.com/docs/postman/collections/creating_collections/
Here is the way to do it:
Example for month:
function getMonth(date) {
var month = date.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
You can also extend Date
object with such function:
Date.prototype.getMonthFormatted = function() {
var month = this.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
Just in case it may help somebody, you may also try this animator ViewPropertyAnimator as below
myView.animate().x(50f).y(100f);
myView.animate().translateX(pixelInScreen)
Note: This pixel is not relative to the view. This pixel is the pixel position in the screen.
credits to bpr10 answer
HomeBrew versions has been removed and formulaes have been emptied. Therefore, my advice is to install it manually following the following steps.
For the time being you will need to build and install the Protocol Buffers toolset manually.
Download source code: https://github.com/google/protobuf/releases/download/v2.4.1/protobuf-2.4.1.tar.gz
tar xvfz protobuf-2.4.1.tar.gz
cd protobuf-2.4.1
Run ./configure
Edit src/google/protobuf/message.cc, add #include at the top of the file
Run make
command from root of the folder, i.e. protobuf-2.4.1/
Run sudo make install
Run /usr/local/bin/protoc --version
to check the version of protobuf compiler version
The terminal output should be:
Version: libprotoc 2.4.1
If you are sure that it is not a typo spelling-wise, perhaps it is a typo case-wise.
What collation are you using? Check it.
well i found out the mistake i was committing i was adding a group to the project instead of adding real directory for more instructions
I am using AngleSharp and have been very satisfied with it.
Here is a simple example how to fetch a page:
var config = Configuration.Default.WithDefaultLoader();
var document = await BrowsingContext.New(config).OpenAsync("https://www.google.com");
And now you have a web page in document variable. Then you can easily access it by LINQ or other methods. For example if you want to get a string value from a HTML table:
var someStringValue = document.All.Where(m =>
m.LocalName == "td" &&
m.HasAttribute("class") &&
m.GetAttribute("class").Contains("pid-1-bid")
).ElementAt(0).TextContent.ToString();
To use CSS selectors please see AngleSharp examples.
$("#pageCSS").attr('href', './css/new_css.css');
I had to do: c:\Users\xxxx>c:/python27/scripts/pip install openpyxl
I had to save the openpyxl files in the scripts folder.
Starting in Android Marshmallow, we need to request the user for specific permissions. We can also check through code if the permission is already given. Here is a list of commonly needed permissions:
android.permission_group.CALENDAR
- android.permission.READ_CALENDAR
- android.permission.WRITE_CALENDAR
android.permission_group.CAMERA
- android.permission.CAMERA
android.permission_group.CONTACTS
- android.permission.READ_CONTACTS
- android.permission.WRITE_CONTACTS
- android.permission.GET_ACCOUNTS
android.permission_group.LOCATION
- android.permission.ACCESS_FINE_LOCATION
- android.permission.ACCESS_COARSE_LOCATION
android.permission_group.MICROPHONE
- android.permission.RECORD_AUDIO
android.permission_group.PHONE
- android.permission.READ_PHONE_STATE
- android.permission.CALL_PHONE
- android.permission.READ_CALL_LOG
- android.permission.WRITE_CALL_LOG
- android.permission.ADD_VOICEMAIL
- android.permission.USE_SIP
- android.permission.PROCESS_OUTGOING_CALLS
android.permission_group.SENSORS
- android.permission.BODY_SENSORS
android.permission_group.SMS
- android.permission.SEND_SMS
- android.permission.RECEIVE_SMS
- android.permission.READ_SMS
- android.permission.RECEIVE_WAP_PUSH
- android.permission.RECEIVE_MMS
- android.permission.READ_CELL_BROADCASTS
android.permission_group.STORAGE
- android.permission.READ_EXTERNAL_STORAGE
- android.permission.WRITE_EXTERNAL_STORAGE
Here is sample code to check for permissions:
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.WRITE_CALENDAR)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setMessage("Write calendar permission is necessary to write event!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.WRITE_CALENDAR}, MY_PERMISSIONS_REQUEST_WRITE_CALENDAR);
}
});
} else {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.WRITE_CALENDAR}, MY_PERMISSIONS_REQUEST_WRITE_CALENDAR);
}
}
child: Align(
alignment: Alignment.center,
child: Text(
'Text here',
textAlign: TextAlign.center,
),
),
This produced the best result for me.
I would use the #{}
constructor, as stated by the other answers.
I also want to point out there is a real subtlety here to watch out for here:
2.0.0p247 :001 > first_name = 'jim'
=> "jim"
2.0.0p247 :002 > second_name = 'bob'
=> "bob"
2.0.0p247 :003 > full_name = '#{first_name} #{second_name}'
=> "\#{first_name} \#{second_name}" # not what we expected, expected "jim bob"
2.0.0p247 :004 > full_name = "#{first_name} #{second_name}"
=> "jim bob" #correct, what we expected
While strings can be created with single quotes (as demonstrated by the first_name
and last_name
variables, the #{}
constructor can only be used in strings with double quotes.
Add this at the top of your file:
#!/usr/bin/python
This is a shebang. You can read more about it on Wikipedia.
After that, you must make the file executable via
chmod +x your_script.py
Google's Crawlable Ajax Spec, as referenced in the other answers here, is basically the answer.
If you're interested in how other search engines and social bots deal with the same issues I wrote up the state of art here: http://blog.ajaxsnapshots.com/2013/11/googles-crawlable-ajax-specification.html
I work for a https://ajaxsnapshots.com, a company that implements the Crawlable Ajax Spec as a service - the information in that report is based on observations from our logs.
Another option is winsw: https://github.com/kohsuke/winsw/
Configure an xml file to specify the service name, what to execute, any arguments etc. And use the exe to install. Example xml: https://github.com/kohsuke/winsw/tree/master/examples
I prefer this to nssm, because it is one lightweight exe; and the config xml is easy to share/commit to source code.
PS the service is installed by running your-service.exe install
What you put inside the </dependencies>
tag of the root pom will be included by all child modules of the root pom. If all your modules use that dependency, this is the way to go.
However, if only 3 out of 10 of your child modules use some dependency, you do not want this dependency to be included in all your child modules. In that case, you can just put the dependency inside the </dependencyManagement>
. This will make sure that any child module that needs the dependency must declare it in their own pom file, but they will use the same version of that dependency as specified in your </dependencyManagement>
tag.
You can also use the </dependencyManagement>
to modify the version used in transitive dependencies, because the version declared in the upper most pom file is the one that will be used. This can be useful if your project A includes an external project B v1.0 that includes another external project C v1.0. Sometimes it happens that a security breach is found in project C v1.0 which is corrected in v1.1, but the developers of B are slow to update their project to use v1.1 of C. In that case, you can simply declare a dependency on C v1.1 in your project's root pom inside `, and everything will be good (assuming that B v1.0 will still be able to compile with C v1.1).
Cast it as an int and subtract
$integer = (int)$your_number;
$decimal = $your_number - $integer;
Or just to get the decimal for comparison
$decimal = $your_number - (int)$your_number
The hidden character is probably BOM. The explanation to the problem and the solution can be found here, credits to James Schubert, based on an answer by James Brankin found here.
Though the previous answer does remove the hidden character, it also removes the whole first line. The more precise version would be:
string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}
I encountered this problem when fetching an XSLT file from Azure blob and loading it into an XslCompiledTransform object. On my machine the file looked just fine, but after uploading it as a blob and fetching it back, the BOM character was added.
As stated in an article by Slicehost:
User setup
So let's start by adding the main user to the Apache user group:
sudo usermod -a -G www-data demo
That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.
You will need to log out and log back in again to enable the group change.
Check the groups now:
groups ... # demo www-data
So now I am a member of two groups: My own (demo) and the Apache group (www-data).
Folder setup
Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).
Let's set that up:
sudo chgrp -R www-data /home/demo/public_html
As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.
If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.
Setgid
Good so far, but remember the command we just gave only affects existing folders. What about anything new?
We can set the ownership so anything new is also in the 'www-data' group.
The first command will change the permissions for the public_html directory to include the "setgid" bit:
sudo chmod 2750 /home/demo/public_html
That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.
If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:
sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads
The permissions only need to be set once as new files will automatically be assigned the correct ownership.
As introduced in Angular 1.3
you can use ng-model-options attribute:
<input
id="searchText"
type="search"
placeholder="live search..."
ng-model="searchText"
ng-model-options="{ debounce: 250 }"
/>
Here is the simple arraylist example for insertion at specific index
ArrayList<Integer> str=new ArrayList<Integer>();
str.add(0);
str.add(1);
str.add(2);
str.add(3);
//Result = [0, 1, 2, 3]
str.add(1, 11);
str.add(2, 12);
//Result = [0, 11, 12, 1, 2, 3]
I wanted to do the same thing. The best I could find was @MicTech's solution. However, as pointed out by @MotoWilliams this does not survive any updates made by Git to the .gitconfig file which replaces the link with a new file containing only the new settings.
I solved this by writing the following PowerShell script and running it in my profile startup script. Each time it is run it copies any settings that have been added to the user's .gitconfig to the global one and then replaces all the text in the .gitconfig file with and [include] header that imports the global file.
I keep the global .gitconfig file in a repo along with a lot of other global scripts and tools. All I have to do is remember to check in any changes that the script appends to my global file.
This seems to work pretty transparently for me. Hope it helps!
Sept 9th: Updated to detect when new entries added to the config file are duplicates and ignore them. This is useful for tools like SourceTree which will write new updates if they cannot find existing ones and do not follow includes.
function git-config-update
{
$localPath = "$env:USERPROFILE\.gitconfig".replace('\', "\\")
$globalPath = "C:\src\github\Global\Git\gitconfig".replace('\', "\\")
$redirectAutoText = "# Generated file. Do not edit!`n[include]`n path = $globalPath`n`n"
$localText = get-content $localPath
$diffs = (compare-object -ref $redirectAutoText.split("`n") -diff ($localText) |
measure-object).count
if ($diffs -eq 0)
{
write-output ".gitconfig unchanged."
return
}
$skipLines = 0
$diffs = (compare-object -ref ($redirectAutoText.split("`n") |
select -f 3) -diff ($localText | select -f 3) | measure-object).count
if ($diffs -eq 0)
{
$skipLines = 4
write-warning "New settings appended to $localPath...`n "
}
else
{
write-warning "New settings found in $localPath...`n "
}
$localLines = (get-content $localPath | select -Skip $skipLines) -join "`n"
$newSettings = $localLines.Split(@("["), [StringSplitOptions]::RemoveEmptyEntries) |
where { ![String]::IsNullOrWhiteSpace($_) } | %{ "[$_".TrimEnd() }
$globalLines = (get-content $globalPath) -join "`n"
$globalSettings = $globalLines.Split(@("["), [StringSplitOptions]::RemoveEmptyEntries)|
where { ![String]::IsNullOrWhiteSpace($_) } | %{ "[$_".TrimEnd() }
$appendSettings = ($newSettings | %{ $_.Trim() } |
where { !($globalSettings -contains $_.Trim()) })
if ([string]::IsNullOrWhitespace($appendSettings))
{
write-output "No new settings found."
}
else
{
echo $appendSettings
add-content $globalPath ("`n# Additional settings added from $env:COMPUTERNAME on " + (Get-Date -displayhint date) + "`n" + $appendSettings)
}
set-content $localPath $redirectAutoText -force
}
Try this:
<?php
$servername = "localhost";
$database = "database";
$username = "user";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
It certainly is! You'll have to loop through the array and print out each item individually.
Same everyday problem.
I just created a simple vc project to solve this problem.
It copies the file as Base64 encoded data directly to the clipboard, and then this can be pasted into the PuTTY console and decoded on the remote side.
This solution is for relatively small files (relative to the connection speed to your remote console).
Download clip_b64.exe
and place it in the SendTo folder (or a .lnk
shortcut to it). To open this folder, in the address bar of the explorer, enter shell:sendto
or %appdata%\Microsoft\Windows\SendTo
.
You may need to install VC 2017 redist to run it, or use the statically linked clip_b64s.exe
execution.
In the File Explorer, right-click the file you are transferring to open the context menu, then go to the "Send To" section and select Clip_B64
from the list.
Run the shell command base64 -d > file-name-you-want
and right-click in the console (or press Shift + Insert
) to place the clipboard content in it, and then press Ctrl + D
to finish.
voila
If your skype is open, Quit skype and try,
or
Go to your xampp/wamp installed, search for httpd.conf. Open that file using textpad/notepad, search for Listen or 80 , update listen port to 8081 and save the file. Restart xampp/wamp, start the servers.
or
follow below steps in skype
Another way would be to use pandas "DateOffset" class
link:-https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.tseries.offsets.DateOffset.html
Using ASGM's code(above in the answers):
from datetime import datetime
import pandas as pd
your_date_string = "April 1, 2012"
format_string = "%B %d, %Y"
datetime_object = datetime.strptime(your_date_string, format_string).date()
new_date = datetime_object + pd.DateOffset(years=1)
new_date.date()
It will return the datetime object with the added year.
Something like this:-
datetime.date(2013, 4, 1)
Tie::File
is what you need:
Synopsis
# This file documents Tie::File version 0.98 use Tie::File; tie @array, 'Tie::File', 'filename' or die ...; $array[13] = 'blah'; # line 13 of the file is now 'blah' print $array[42]; # display line 42 of the file $n_recs = @array; # how many records are in the file? $#array -= 2; # chop two records off the end for (@array) { s/PERL/Perl/g; # Replace PERL with Perl everywhere in the file } # These are just like regular push, pop, unshift, shift, and splice # Except that they modify the file in the way you would expect push @array, new recs...; my $r1 = pop @array; unshift @array, new recs...; my $r2 = shift @array; @old_recs = splice @array, 3, 7, new recs...; untie @array; # all finished
The best way is to use the ncurses library - though this might be a sledgehammer to crack a nut if you just want to output a simple coloured string
String test = "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);
while(listbox.Items.Remove(s)) ;
should work, as well. However, I think the backwards solution is the fastest.
You can pass string parameters to JavaScript functions like below code:
I passed three parameters where the third one is a string parameter.
var btn ="<input type='button' onclick='RoomIsReadyFunc(" + ID + "," + RefId + ",\"" + YourString + "\");' value='Room is Ready' />";
// Your JavaScript function
function RoomIsReadyFunc(ID, RefId, YourString)
{
alert(ID);
alert(RefId);
alert(YourString);
}
It can happen because of one of the three reasons:-
1) Missing VC++ installation: Install All versions of VC++ redistribution packages VC9, VC10, VC11, VC13, VC14 and VC15. See the link provided at the end for download link. If you have a 64-bit Windows, you must install both 32 and 64bit versions of each VisualC++ package, even if you do not use Wampserver 64 bit.
2) You forgot to provide Admin Privileges to WAMP Server : Launch and Install with the "Run as administrator" option, very important.
3) WAMP, IIS and Skype fighting over same port :
VC9 Packages (Visual C++ 2008 SP1)
http://www.microsoft.com/en-us/download/details.aspx?id=5582 http://www.microsoft.com/en-us/download/details.aspx?id=2092
VC10 Packages (Visual C++ 2010 SP1) http://www.microsoft.com/en-us/download/details.aspx?id=8328 http://www.microsoft.com/en-us/download/details.aspx?id=13523
VC11 Packages (Visual C++ 2012 Update 4) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/en-us/download/details.aspx?id=30679
VC13 Packages] (Visual C++ 2013) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: https://www.microsoft.com/en-us/download/details.aspx?id=40784
VC14 Packages (Visual C++ 2015 Update 3) The two files vcredist_x86.exe and vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/fr-fr/download/details.aspx?id=53840
VC15 Redistribuable (Visual C++ 2017) https://go.microsoft.com/fwlink/?LinkId=746571 Visual C++ Redistributable Packages for Visual Studio 2017 x86 https://go.microsoft.com/fwlink/?LinkId=746572
You have to use MySQLi, below code works well
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
You can use sub query way of codeigniter to do this for this purpose you will have to hack codeigniter. like this
Go to system/database/DB_active_rec.php
Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now subquery writing in available And now here is your query with active record
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
$this->db->_reset_select();
// And now your main query
$this->db->select("*");
$this->db->where_in("$subQuery");
$this->db->where('code !=', 'B');
$this->db->get('myTable');
And the thing is done. Cheers!!!
Note : While using sub queries you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Watch this too
How can I rewrite this SQL into CodeIgniter's Active Records?
Note : In Codeigntier 3 these functions are already public so you do not need to hack them.
URLs use forward slashes (/), not backward ones (as windows). Try:
serverURLS = "https://abc.my.domain.com:55555/update";
The reason why you get the error is that the URL class can't parse the host part of the string and therefore, host
is null
.
Where is this info kept ("this connection is between computer
A
and serverF
")?
A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.
HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.
This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.
When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection
No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.
which is only for my session ?
Does it mean that no one else can use that connection
That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.
If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?
Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:
if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)
An typical keep-alive response looks like this:
Keep-Alive: timeout=15, max=100
See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):
A host sets the value of the timeout
parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.
The max
parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.
However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.
Further into direction pointed out by Brian and based on sh (1.0.8+)
from sh import cd, ls
cd('/tmp')
print ls()
On technologies with message loops (not sure if ASP is one of them), you can block the loop and process messages until the task is over, and use ContinueWith to unblock the code:
public void WaitForTask(Task task)
{
DispatcherFrame frame = new DispatcherFrame();
task.ContinueWith(t => frame.Continue = false));
Dispatcher.PushFrame(frame);
}
This approach is similar to blocking on ShowDialog and still keeping the UI responsive.
sizeof(buffer) is the size of a pointer on your last line NOT the actual size of the buffer. You need to use "length" that you already established instead
For me, this started to happen after merge conflict.
I tried to clean and remove build folder, but none of it helped. This issue kept happening regardless. Then I relinked the reference by deleting the groups that was problematic and re-added to the project and it worked.
The Log class:
API for sending log output.
Generally, use the
Log.v()
Log.d()
Log.i()
Log.w()
andLog.e()
methods.The order in terms of verbosity, from least to most is
ERROR
,WARN
,INFO
,DEBUG
,VERBOSE
. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.
Outside of Android, System.out.println(String msg)
is used.
@webdeb's answer didn't work for me, I hit an unexpected token
error when compiling ES6 with Babel, doing named default exports.
This worked for me, however:
// Foo.js
export default Foo
...
// bundle.js
export { default as Foo } from './Foo'
export { default as Bar } from './Bar'
...
// and import somewhere..
import { Foo, Bar } from './bundle'
When multiple threads need to check and change the boolean. For example:
if (!initialized) {
initialize();
initialized = true;
}
This is not thread-safe. You can fix it by using AtomicBoolean
:
if (atomicInitialized.compareAndSet(false, true)) {
initialize();
}
I only needed the environment variables locally to invoke my test command, here's an example setting multiple environment vars in a bash shell, and escaping the dollar sign in make
.
SHELL := /bin/bash
.PHONY: test tests
test tests:
PATH=./node_modules/.bin/:$$PATH \
JSCOVERAGE=1 \
nodeunit tests/
You can use
change config to cookie & type your password in ' ' in password like bellow
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'your password';
Then save & type on browser localhost/phpmyadmin/
Enter your given password & enjoy
Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
The easiest solution to animate the DOM elements is using CSS transitions/animations but I think you already know that and you try to use canvas to do stuff CSS doesn't let you to do. What about CSS custom filters? you can transform your elements in any imaginable way if you know how to write shaders. Some other link and don't forget to check the CSS filter lab.
Note: As you can probably imagine browser support is bad.
The instanceof-operator is called is
in Dart. The spec isn't exactly friendly to a casual reader, so the best description right now seems to be http://www.dartlang.org/articles/optional-types/.
Here's an example:
class Foo { }
main() {
var foo = new Foo();
if (foo is Foo) {
print("it's a foo!");
}
}
Some AWS services are just available in specific regions that do not match your actual region. If this is the case you can override the standard setting by adding the region to your actual cli command.
This might be a handy solution for people that do not want to change their default region in the config file. IF your general config file is not set: Please check the suggestions above.
In this example the region is forced to eu-west-1 (e.g. Ireland):
aws s3 ls --region=eu-west-1
Tested and used with aws workmail to delete users:
aws workmail delete-user --region=eu-west-1 --organization-id [org-id] --user-id [user-id]
I derived the idea from this thread and it works perfect for me - so I wanted to share it. Hope it helps!
while true; do
sleep 5
ls -l
done
Following the argument about Math.ceil(value/10d)
and (value+9)/10
I ended up coding a proper non-dead code, non-interpret mode benchmark.
I've been telling that writing micro benchmark is not an easy task. The code below illustrates this:
00:21:40.109 starting up....
00:21:40.140 doubleCeil: 19444599
00:21:40.140 integerCeil: 19444599
00:21:40.140 warming up...
00:21:44.375 warmup doubleCeil: 194445990000
00:21:44.625 warmup integerCeil: 194445990000
00:22:27.437 exec doubleCeil: 1944459900000, elapsed: 42.806s
00:22:29.796 exec integerCeil: 1944459900000, elapsed: 2.363s
The benchmark is in Java since I know well how Hotspot optimizes and ensures it's a fair result. With such results, no statistics, noise or anything can taint it.
Integer ceil is insanely much faster.
The code
package t1;
import java.math.BigDecimal;
import java.util.Random;
public class Div {
static int[] vals;
static long doubleCeil(){
int[] v= vals;
long sum = 0;
for (int i=0;i<v.length;i++){
int value = v[i];
sum+=Math.ceil(value/10d);
}
return sum;
}
static long integerCeil(){
int[] v= vals;
long sum = 0;
for (int i=0;i<v.length;i++){
int value = v[i];
sum+=(value+9)/10;
}
return sum;
}
public static void main(String[] args) {
vals = new int[7000];
Random r= new Random(77);
for (int i = 0; i < vals.length; i++) {
vals[i] = r.nextInt(55555);
}
log("starting up....");
log("doubleCeil: %d", doubleCeil());
log("integerCeil: %d", integerCeil());
log("warming up...");
final int warmupCount = (int) 1e4;
log("warmup doubleCeil: %d", execDoubleCeil(warmupCount));
log("warmup integerCeil: %d", execIntegerCeil(warmupCount));
final int execCount = (int) 1e5;
{
long time = System.nanoTime();
long s = execDoubleCeil(execCount);
long elapsed = System.nanoTime() - time;
log("exec doubleCeil: %d, elapsed: %.3fs", s, BigDecimal.valueOf(elapsed, 9));
}
{
long time = System.nanoTime();
long s = execIntegerCeil(execCount);
long elapsed = System.nanoTime() - time;
log("exec integerCeil: %d, elapsed: %.3fs", s, BigDecimal.valueOf(elapsed, 9));
}
}
static long execDoubleCeil(int count){
long sum = 0;
for(int i=0;i<count;i++){
sum+=doubleCeil();
}
return sum;
}
static long execIntegerCeil(int count){
long sum = 0;
for(int i=0;i<count;i++){
sum+=integerCeil();
}
return sum;
}
static void log(String msg, Object... params){
String s = params.length>0?String.format(msg, params):msg;
System.out.printf("%tH:%<tM:%<tS.%<tL %s%n", new Long(System.currentTimeMillis()), s);
}
}
Open inspect mode before navigating to the page. It worked.hehe
Colon does not have special meaning in a character class and does not need to be escaped. According to the PHP regex docs, the only characters that need to be escaped in a character class are the following:
All non-alphanumeric characters other than
\
,-
,^
(at the start) and the terminating]
are non-special in character classes, but it does no harm if they are escaped.
For more info about Java regular expressions, see the docs.
Here is the solution I was looking for. If you would like to create List2 that contains the difference of the number elements in List1.
list1 = [12, 15, 22, 54, 21, 68, 9, 73, 81, 34, 45]
list2 = []
for i in range(1, len(list1)):
change = list1[i] - list1[i-1]
list2.append(change)
Note that while len(list1)
is 11 (elements), len(list2)
will only be 10 elements because we are starting our for loop from element with index 1 in list1 not from element with index 0 in list1
also, you can fetch all data and count in the blade file. for example:
your code in the controller
$posts = Post::all();
return view('post', compact('posts'));
your code in the blade file.
{{ $posts->count() }}
finally, you can see the total of your posts.
If you use Kotlin, you can add an extension method to Image in the same manner Sri Harsha Chilakapati suggests.
fun Image.toBufferedImage(): BufferedImage {
if (this is BufferedImage) {
return this
}
val bufferedImage = BufferedImage(this.getWidth(null), this.getHeight(null), BufferedImage.TYPE_INT_ARGB)
val graphics2D = bufferedImage.createGraphics()
graphics2D.drawImage(this, 0, 0, null)
graphics2D.dispose()
return bufferedImage
}
And use it like this:
myImage.toBufferedImage()
It's not like that. ArrayList just uses array as internal respentation. If you add more then 60 elements then underlaying array will be exapanded. How ever you can add as much elements to this array as much RAM you have.
Your byte array is too small. Each pixel takes up 4 bytes, not just 1, so multiply your size * 4 so that the array is big enough.
You may try to inherit property from the base class:
var width = 2;_x000D_
var interval = setInterval(function () {_x000D_
var element = document.getElementById('box');_x000D_
width += 0.0625;_x000D_
element.style.width = width + 'em';_x000D_
if (width >= 7) clearInterval(interval);_x000D_
}, 50);
_x000D_
.box {_x000D_
/* Set property */_x000D_
width:4em;_x000D_
height:2em;_x000D_
background-color:#d42;_x000D_
position:relative;_x000D_
}_x000D_
.box:after {_x000D_
/* Inherit property */_x000D_
width:inherit;_x000D_
content:"";_x000D_
height:1em;_x000D_
background-color:#2b4;_x000D_
position:absolute;_x000D_
top:100%;_x000D_
}
_x000D_
<div id="box" class="box"></div>
_x000D_
you want to use include_once() or require_once(). The other option would be to create an additional file with all your class includes in the correct order so they don't need to call includes themselves:
"classes.php"
include 'database.php';
include 'parent.php';
include 'child1.php';
include 'child2.php';
Then you just need:
require_once('classes.php');
I faced the same issue and got it working.
I think it is because when you import a project, build target is not set in the project properties which then default to the value used in manifest file. Most likely, you already have installed a later android API with your SDK.
The solution is to enable build target toward your installed API level (but keep the minimum api support as specified in the manifest file). TO do this, in project properties, go to android, and from "Project Build Target", pick a target name.
This is what worked for me (Intellij Idea 2018.1.2):
1) Navigate to: File -> Settings -> Build, Execution, Deployment -> Build Tools -> Gradle
2) Gradle JVM: change to version 1.8
3) Re-run the gradle task
In application:didReceiveRemoteNotification:
check whether you have received the notification when your app is in the foreground or background.
If it was received in the background, launch the app from the notification.
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
NSLog(@"Notification received by running app");
} else {
NSLog(@"App opened from Notification");
}
}
As of June 2016, the Download ZIP button is still under the <> Code tab, however it is now inside a button with two options clone or download:
Is this code snippet work for you?
if (!count($_SESSION)>0) {
session_start();
}
hashCode()
method is not for providing a unique identifier for an object. It rather digests the object's state (i.e. values of member fields) to a single integer. This value is mostly used by some hash based data structures like maps and sets to effectively store and retrieve objects.
If you need an identifier for your objects, I recommend you to add your own method instead of overriding hashCode
. For this purpose, you can create a base interface (or an abstract class) like below.
public interface IdentifiedObject<I> {
I getId();
}
Example usage:
public class User implements IdentifiedObject<Integer> {
private Integer studentId;
public User(Integer studentId) {
this.studentId = studentId;
}
@Override
public Integer getId() {
return studentId;
}
}
ECMAScript 6 introduces the easily polyfillable Object.assign
:
The
Object.assign()
method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
The own length
property of the array is not copied because it isn't enumerable.
Also, you can use ES8 spread syntax on objects to achieve the same result:
{ ...['a', 'b', 'c'] }
I agree with above answers, Here is a complete read and write sample for anyone who needs it.
router.post('/', function(req, res, next) {
console.log(req.body);
var id = Math.floor((Math.random()*100)+1);
var tital = req.body.title;
var description = req.body.description;
var mynotes = {"Id": id, "Title":tital, "Description": description};
fs.readFile('db.json','utf8', function(err,data){
var obj = JSON.parse(data);
obj.push(mynotes);
var strNotes = JSON.stringify(obj);
fs.writeFile('db.json',strNotes, function(err){
if(err) return console.log(err);
console.log('Note added');
});
})
});
You can pass the event as argument to the function and then prevent the default behaviour.
var OnSubmitTest = React.createClass({
render: function() {
doSomething = function(event){
event.preventDefault();
alert('it works!');
}
return <form onSubmit={this.doSomething}>
<button>Click me</button>
</form>;
}
});
Refresh document every 300 seconds using HTML Meta tag add this inside the head tag of the page
<meta http-equiv="refresh" content="300">
Using Script:
setInterval(function() {
window.location.reload();
}, 300000);
Php Version: 5.6
Symfony version: 2.3
Guzzle: 5.0
I had an experience recently about sending json with Guzzle. I use Symfony 2.3 so my guzzle version can be a little older.
I will also show how to use debug mode and you can see the request before sending it,
When i made the request as shown below got the successfull response;
use GuzzleHttp\Client;
$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
"Content-Type" => "application/json"
];
$body = json_encode($requestBody);
$client = new Client();
$client->setDefaultOption('headers', $headers);
$client->setDefaultOption('verify', false);
$client->setDefaultOption('debug', true);
$response = $client->post($endPoint, array('body'=> $body));
dump($response->getBody()->getContents());
DataRow's are nice in the way that they have their underlying table linked to them. With the underlying table you can verify that a specific row has a specific column in it.
If DataRow.Table.Columns.Contains("column") Then
MsgBox("YAY")
End If
I usually use selectors in my main stylesheet, then make an ie6 specific .js (jquery) file that adds a class to all of the input types. Example:
$(document).ready(function(){
$("input[type='text']").addClass('text');
)};
And then just duplicate my styles in the ie6 specific stylesheet using the classes. That way the actual markup is a little bit cleaner.
Based on @blushrt 's great answer I will update this response. Just using -
$("#Select_ID").val(id);
works if you've preloaded everything you need to the selector.
As some of you already said, the easiest way is to update Node.js through the Node.js package manager, npm. If you are a Linux (Debian-based in my case) user I would suggest to add these lines to your .bashrc
file (in home directory):
function nodejsupdate() {
ARGC=$#
version=latest
if [ $ARGC != 0 ]; then
version=$1
fi
sudo npm cache clean -f
sudo npm install -g n
sudo n $version
}
Restart your terminal after saving and write nodejsupdate
to update to the latest version of Node.js or nodejsupdate v6.0.0
(for example) to update to a specific version of Node.js.
BONUS: Update npm (add these lines to .bashrc
)
function npmupdate() {
sudo npm i npm -g
}
After restarting the terminal write npmupdate
to update your node package manager to the latest version.
Now you can update Node.js and npm through your terminal (easier).
Mesos and Kubernetes can both be used to manage a cluster of machines and abstract away the hardware.
Mesos, by design, doesn't provide you with a scheduler (to decide where and when to run processes and what to do if the process fails), you can use something like Marathon or Chronos, or write your own.
Kubernetes will do scheduling for you out of the box, and can be used as a scheduler for Mesos (please correct me if I'm wrong here!) which is where you can use them together. Mesos can have multiple schedulers sharing the same cluster, so in theory you could run kubernetes and chronos together on the same hardware.
Super simplistically: if you want control over how your containers are scheduled, go for Mesos, otherwise Kubernetes rocks.
Here you go:
$('td[id^="' + value +'"]')
so if the value is for instance 'foo'
, then the selector will be 'td[id^="foo"]'
.
Note that the quotes are mandatory: [id^="...."]
.
Source: http://api.jquery.com/attribute-starts-with-selector/
Do make sure that you haven't written your unit tests in a .NET Standard 2.0 Class Library. The visualstudio runner does not support running tests in netstandard2.0 class libraries at the time of this writing.
Check here for the Test Runner Compatibility matrix:
For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.
Not always. NaN is a counterexample. But usually, identity (is
) implies equality (==
). The converse is not true: Two distinct objects can have the same value.
Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values?
You use ==
when comparing values and is
when comparing identities.
When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with is
, but don't rely on it.
For boolean values, you shouldn't be doing comparisons at all. Instead of:
if x == True:
# do something
write:
if x:
# do something
For comparing against None
, is None
is preferred over == None
.
I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id.
Yes, that's exactly what it's for.
If elements are always nearly sorted as in your example then builtin .sort()
(timsort) should be fast:
>>> a = [1,1,2]
>>> b = [1,2,2]
>>> a.sort()
>>> b.sort()
>>> a == b
False
If you don't want to sort inplace you could use sorted()
.
In practice it might always be faster then collections.Counter()
(despite asymptotically O(n)
time being better then O(n*log(n))
for .sort()
). Measure it; If it is important.
Not sure if there's terrible reasons to do this or not, but it seems to work with me on the latest version of Chrome/Firefox without any visible performance problems with quite a lot of elements on the page.
*:not(:hover)>.parent-hover-show{
display:none;
}
But this way, all you need is to apply parent-hover-show
to an element and the rest is taken care of, and you can keep whatever default display type you want without it always being "block" or making multiple classes for each type.
E-mail addresses are very difficult to verify correctly with a mere regex. Here is a pretty scary regex that supposedly implements RFC822, chapter 6, the specification of valid e-mail addresses.
Not really an answer, but maybe related to what you're trying to accomplish.
SELECT sc.name +'.'+ ta.name TableName
,SUM(pa.rows) RowCnt
FROM sys.tables ta
INNER JOIN sys.partitions pa
ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
GROUP BY sc.name,ta.name
ORDER BY SUM(pa.rows) DESC
See this:
For the former, convention over configuration. Rails default when you reference another table with
belongs_to :something
is to look for something_id
.
references
, or belongs_to
is actually newer way of writing the former with few quirks.
Important is to remember that it will not create foreign keys for you. In order to do that, you need to set it up explicitly using either:
t.references :something, foreign_key: true
t.belongs_to :something_else, foreign_key: true
or (note the plural):
add_foreign_key :table_name, :somethings
add_foreign_key :table_name, :something_elses`
I think you used somehow the right way to show the number only on the keyboard so better try the given line with xml in your edit text and it will work perfectly so here the code is-
android:inputType="number"
In case any doubt you can again ask to me i'll try to completely sort out your problem. Thanks
Verify the following steps.
Those things should fix the problem
I may have missed something here, but why can't you just declare your string with the desired size? For example, in my VBA code I often use something like:
Dim AString As String * 1024
which provides for a 1k string. Obviously, you can use whatever declaration you like within the larger limits of Excel and available memory etc.
This may be a little inefficient in some cases, and you will probably wish to use Trim(AString) like constructs to obviate any superfluous trailing blanks. Still, it easily exceeds 256 chars.
Given you have bash
on your android device, you can use this bash function :
function androidCodeName {
androidRelease=$(getprop ro.build.version.release)
androidCodeName=$(getprop ro.build.version.codename)
# Time "androidRelease" x10 to test it as an integer
case $androidRelease in
[0-9].[0-9]|[0-9].[0-9].|[0-9].[0-9].[0-9]) androidRelease=$(echo $androidRelease | cut -d. -f1-2 | tr -d .);;
[0-9].) androidRelease=$(echo $androidRelease | sed 's/\./0/');;
[0-9]) androidRelease+="0";;
esac
[ -n "$androidRelease" ] && [ $androidCodeName = REL ] && {
# Do not use "androidCodeName" when it equals to "REL" but infer it from "androidRelease"
androidCodeName=""
case $androidRelease in
10) androidCodeName+=NoCodename;;
11) androidCodeName+="Petit Four";;
15) androidCodeName+=Cupcake;;
20|21) androidCodeName+=Eclair;;
22) androidCodeName+=FroYo;;
23) androidCodeName+=Gingerbread;;
30|31|32) androidCodeName+=Honeycomb;;
40) androidCodeName+="Ice Cream Sandwich";;
41|42|43) androidCodeName+="Jelly Bean";;
44) androidCodeName+=KitKat;;
50|51) androidCodeName+=Lollipop;;
60) androidCodeName+=Marshmallow;;
70|71) androidCodeName+=Nougat;;
80|81) androidCodeName+=Oreo;;
90) androidCodeName+=Pie;;
100) androidCodeName+=ToBeReleased;;
*) androidCodeName=unknown;;
esac
}
echo $androidCodeName
}
You need to remove the
min-height:440px;
to
height:440px;
and then add
overflow: auto;
property to the class of the required div
I faced this problem in a Framework7 & Cordova project. I tried all the solutions above. They did not solve my problem.
In my case, I was using 10+ css animations on the same page with infinite rotation (transform). I had to remove the animations. It is ok now with the lack of some visual features.
If the solutions above do not help you, you may start eliminating some animations.
In a maven project create a file src/main/resources/application.yml
with the following content:
spring.profiles: integration
# use local or embedded mongodb at localhost:27017
---
spring.profiles: production
spring.data.mongodb.uri: mongodb://<user>:<passwd>@<host>:<port>/<dbname>
Spring Boot will automatically use this file to configure your application. Then you can start your spring boot application either with the integration profile (and use your local MongoDB)
java -jar -Dspring.profiles.active=integration your-app.jar
or with the production profile (and use your production MongoDB)
java -jar -Dspring.profiles.active=production your-app.jar
Use:
SELECT t1.Notes,
t2.Name
FROM Table1 t1
JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')
using System.Globalization;
LblMonth.Text = DateTime.Now.Month.ToString();
DateTimeFormatInfo dinfo = new DateTimeFormatInfo();
int month = Convert.ToInt16(LblMonth.Text);
LblMonth.Text = dinfo.GetMonthName(month);
If pip "says" six is installed but you're still getting:
ImportError: No module named six.moves
try re-installing six (worked for me):
pip uninstall six
pip install six
Could you provide a whole makefile? But right now I can tell - you should check that "install" target already exists. So, check Makefile whether it contains a
install: (anything there)
line. If not, there is no such target and so make has right. Probably you should use just "make" command to compile and then use it as is or install yourself, manually.
Install is not any standard of make, it is just a common target, that could exists, but not necessary.
Threads share data and code while processes do not. The stack is not shared for both.
Processes can also share memory, more precisely code, for example after a Fork()
, but this is an implementation detail and (operating system) optimization. Code shared by multiple processes will (hopefully) become duplicated on the first write to the code - this is known as copy-on-write. I am not sure about the exact semantics for the code of threads, but I assume shared code.
Process Thread Stack private private Data private shared Code private1 shared2
1 The code is logically private but might be shared for performance reasons. 2 I am not 100% sure.
You could specify the width of all but the last table cells and add a table-layout:fixed and a width to the table.
You could set
table tr ul.actions {margin: 0; white-space:nowrap;}
(or set this for the last TD as Sander suggested instead).
This forces the inline-LIs not to break. Unfortunately this does not lead to a new width calculation in the containing UL (and this parent TD), and therefore does not autosize the last TD.
This means: if an inline element has no given width, a TD's width is always computed automatically first (if not specified). Then its inline content with this calculated width gets rendered and the white-space
-property is applied, stretching its content beyond the calculated boundaries.
So I guess it's not possible without having an element within the last TD with a specific width.
Insert your fetched values into an array instead of echoing.
Use file_put_contents()
and insert json_encode($rows)
into that file, if $rows
is your data.
Depending on your needs, you have a few options here.
If you don't need to do key/value lookups and want to stick with a List<>
, you can make use of Tuple<int, string>
:
List<Tuple<int, string>> mylist = new List<Tuple<int, string>>();
// add an item
mylist.Add(new Tuple<int, string>(someInt, someString));
If you do want key/value lookups, you could move towards a Dictionary<int, string>
:
Dictionary<int, string> mydict = new Dictionary<int, string>();
// add an item
mydict.Add(someInt, someString);
All the other answers about setting only the JAVA_HOME
are not entirely right. Eclipse does namely not consult the JAVA_HOME
. Look closer at the error message:
...in your current PATH
It literally said PATH
, not JAVA_HOME
.
Rightclick My Computer and choose Properties (or press Winkey+Pause), go to the tab Advanced, click the button Environment Variables, in the System Variables list at the bottom select Path
(no, not Classpath
), click Edit and add ;c:\path\to\jdk\bin
to the end of the value.
Alternatively and if not present, you can also add JAVA_HOME
environment variable and make use of it in the PATH
. In the same dialogue click New and add JAVA_HOME
with the value of c:\path\to\jdk
. Then you can add ;%JAVA_HOME%\bin
to end of the value of the Path
setting.
There's no way to stop execution of your code as you would do with a procedural language. You can instead make use of setTimeout and some trickery to get a parametrized timeout:
for (var i = 1; i <= 5; i++) {
var tick = function(i) {
return function() {
console.log(i);
}
};
setTimeout(tick(i), 500 * i);
}
Demo here: http://jsfiddle.net/hW7Ch/
HTML
<div id="container">
<div id="element">
some text
</div>
</div>
CSS
#container {
width: 50%; /* desired width */
}
#element {
height: 0;
padding-bottom: 100%;
}
Random generator = new Random();
int i = generator.nextInt(10) + 1;
Try with this jQuery code that normalize Bootstrap carousel slide heights
function carouselNormalization() {
var items = $('#carousel-example-generic .item'), //grab all slides
heights = [], //create empty array to store height values
tallest; //create variable to make note of the tallest slide
if (items.length) {
function normalizeHeights() {
items.each(function() { //add heights to array
heights.push($(this).height());
});
tallest = Math.max.apply(null, heights); //cache largest value
items.each(function() {
$(this).css('min-height', tallest + 'px');
});
};
normalizeHeights();
$(window).on('resize orientationchange', function() {
tallest = 0, heights.length = 0; //reset vars
items.each(function() {
$(this).css('min-height', '0'); //reset min-height
});
normalizeHeights(); //run it again
});
}
}
/**
* Wait until all the assets have been loaded so a maximum height
* can be calculated correctly.
*/
window.onload = function() {
carouselNormalization();
}
_x000D_
Just one more line for @tofutim answer ... if you want custom field name for concatenated row ...
SELECT
(
col1 || '-' || SUBSTR('00' || col2, -2, 2) | '-' || SUBSTR('0000' || col3, -4, 4)
) AS my_column
FROM
mytable;
Tested on SQLite 3.8.8.3, Thanks!
curl -u username:password http://
curl -u username http://
From the documentation page:
-u, --user <user:password>
Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.
If you simply specify the user name, curl will prompt for a password.
The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.
When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.
When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.
To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.
If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".
If this option is used several times, the last one will be used.
http://curl.haxx.se/docs/manpage.html#-u
Note that you do not need --basic
flag as it is the default.
Check to see if your gradle is offline. Preferences-ProjectSettings-Gradle. If you're trying to add a library while offline, you'll see that error. Also, try Build-Clean, it may provide you with more detail.
I know the question has been answered, but in my case I was trying to send the content of a text file to the Slack Webhook api and for some reason the above answer did not work. Anywho, this is what finally did the trick for me:
curl -X POST -H --silent --data-urlencode "payload={\"text\": \"$(cat file.txt | sed "s/\"/'/g")\"}" https://hooks.slack.com/services/XXX
Use try block in your code like
try
{
// Your code...
// Could also be before try if you know the exception occurs in SaveChanges
context.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
You can check the details here as well
A NullPointerException means that one of the variables you are passing is null, but the code tries to use it like it is not.
For example, If I do this:
Integer myInteger = null;
int n = myInteger.intValue();
The code tries to grab the intValue of myInteger, but since it is null, it does not have one: a null pointer exception happens.
What this means is that your getTask method is expecting something that is not a null, but you are passing a null. Figure out what getTask needs and pass what it wants!
.Text is the formatted cell's displayed value; .Value is the value of the cell possibly augmented with date or currency indicators; .Value2 is the raw underlying value stripped of any extraneous information.
range("A1") = Date
range("A1").numberformat = "yyyy-mm-dd"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2
'results from Immediate window
2018-06-14
6/14/2018
43265
range("A1") = "abc"
range("A1").numberformat = "_(_(_(@"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2
'results from Immediate window
abc
abc
abc
range("A1") = 12
range("A1").numberformat = "0 \m\m"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2
'results from Immediate window
12 mm
12
12
If you are processing the cell's value then reading the raw .Value2 is marginally faster than .Value or .Text. If you are locating errors then .Text will return something like #N/A
as text and can be compared to a string while .Value and .Value2 will choke comparing their returned value to a string. If you have some custom cell formatting applied to your data then .Text may be the better choice when building a report.
I had similar issue when I had to install from github repo, but did not want to install git , etc.
The simple way to do it is using zip archive of the package. Add /zipball/master
to the repo URL:
$ pip install https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading/unpacking https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading master
Running setup.py egg_info for package from https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Installing collected packages: django-debug-toolbar-mongo
Running setup.py install for django-debug-toolbar-mongo
Successfully installed django-debug-toolbar-mongo
Cleaning up...
This way you will make pip work with github source repositories.
As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:
WHILE EXISTS (SELECT 1
FROM YourTable
WHERE <yourCondition>)
DELETE TOP(10000) FROM YourTable
WHERE <yourCondition>
You are most likely not using the correct credentials for the MySQL server. You also need to ensure the user you are connecting as has the correct privileges to view databases/tables, and that you can connect from your current location in network topographic terms (localhost).
Source: Use NATURAL FULL JOIN to compare two tables in SQL by Lukas Eder
Clever approach of using NATURAL FULL JOIN
to detect the same/different rows between two tables.
Example 1 - status flag:
SELECT t1.*, t2.*, CASE WHEN t1 IS NULL OR t2 IS NULL THEN 'Not equal' ELSE 'Equal' END
FROM t1
NATURAL FULL JOIN t2;
Example 2 - filtering rows
SELECT *
FROM (SELECT 't1' AS t1, t1.* FROM t1) t1
NATURAL FULL JOIN (SELECT 't2' AS t2, t2.* FROM t2) t2
WHERE t1 IS NULL OR t2 IS NULL -- show differences
--WHERE t1 IS NOT NULL AND t2 IS NOT NULL -- show the same
changing the width of the image will automatically change the height...
how many pictures do you want to have this functionality? If it's a lot and they all have DIFFERENT Heights you should probably just let the height change as well.
Lets say you have 5 images that have height 400px , in your html give those five tags the class of fixed
.fixed { width: 100%; height: 500px !important }
This should let the width change but keep the height the same.
I always thought that for a task that trivial, I wouldn't want to import anything. But i may be wrong, depending on collections.Counter being faster or not.
items = "Whats the simpliest way to add the list items to a dictionary "
stats = {}
for i in items:
if i in stats:
stats[i] += 1
else:
stats[i] = 1
# bonus
for i in sorted(stats, key=stats.get):
print("%d×'%s'" % (stats[i], i))
I think this may be preferable to using count(), because it will only go over the iterable once, whereas count may search the entire thing on every iteration. I used this method to parse many megabytes of statistical data and it always was reasonably fast.
The %2C
translates to a comma (,
). I saw this while searching for a sentence with a comma in it and on the url, instead of showing a comma, it had %2C
.
vuejs 2
first add this to methods
methods:{
sayHi: function () {
var v = this;
setTimeout(function () {
v.message = "Hi Vue!";
}, 3000);
}
after that call this method on mounted
mounted () {
this.sayHi()
}
If You are a newbie then you can take reference from my code .. what i did was to put on a check so that i could only get the Alphabets and white spaces! You can Repeat the for loop after the second if statement to validate the string again
bool check = false;
Console.WriteLine("Please Enter the Name");
name=Console.ReadLine();
for (int i = 0; i < name.Length; i++)
{
if (name[i]>='a' && name[i]<='z' || name[i]==' ')
{
check = true;
}
else
{
check = false;
break;
}
}
if (check==false)
{
Console.WriteLine("Enter Valid Value");
name = Console.ReadLine();
}
Scripts are loaded in the order you have defined them in the HTML.
Therefore if you first load:
<script type="text/javascript" src="./javascript.js"></script>
without loading jQuery first, then $ is not defined
.
You need to first load jQuery so that you can use it.
I would also recommend placing your scripts at the bottom of your HTML for performance reasons.
SELECT
category,
COUNT(*) AS `num`
FROM
posts
GROUP BY
category
Not tested, but something like this:
var now = new Date();
var str = now.getUTCFullYear().toString() + "/" +
(now.getUTCMonth() + 1).toString() +
"/" + now.getUTCDate() + " " + now.getUTCHours() +
":" + now.getUTCMinutes() + ":" + now.getUTCSeconds();
Of course, you'll need to pad the hours, minutes, and seconds to two digits or you'll sometimes get weird looking times like "2011/12/2 19:2:8."
You can use readlink
on /proc/self/fd/NNN
where NNN is the file descriptor. This will give you the name of the file as it was when it was opened — however, if the file was moved or deleted since then, it may no longer be accurate (although Linux can track renames in some cases). To verify, stat
the filename given and fstat
the fd you have, and make sure st_dev
and st_ino
are the same.
Of course, not all file descriptors refer to files, and for those you'll see some odd text strings, such as pipe:[1538488]
. Since all of the real filenames will be absolute paths, you can determine which these are easily enough. Further, as others have noted, files can have multiple hardlinks pointing to them - this will only report the one it was opened with. If you want to find all names for a given file, you'll just have to traverse the entire filesystem.
an array does not contain index when elements are associative. An array in php can contain mixed values like this:
$var = array("apple", "banana", "foo" => "grape", "carrot", "bar" => "donkey");
print_r($var);
Gives you:
Array
(
[0] => apple
[1] => banana
[foo] => grape
[2] => carrot
[bar] => donkey
)
What are you trying to achieve since you need the index value in an associative array?
It's interesting that people always use 'real world problem' to make joke on the definition in theoretical science.
If set has order, you first need to figure out the following problems. If your list has duplicate elements, what should the order be when you turn it into a set? What is the order if we union two sets? What is the order if we intersect two sets with different order on the same elements?
Plus, set is much faster in searching for a particular key which is very good in sets operation (and that's why you need a set, but not list).
If you really care about the index, just keep it as a list. If you still want to do set operation on the elements in many lists, the simplest way is creating a dictionary for each list with the same keys in the set along with a value of list containing all the index of the key in the original list.
def indx_dic(l):
dic = {}
for i in range(len(l)):
if l[i] in dic:
dic.get(l[i]).append(i)
else:
dic[l[i]] = [i]
return(dic)
a = [1,2,3,4,5,1,3,2]
set_a = set(a)
dic_a = indx_dic(a)
print(dic_a)
# {1: [0, 5], 2: [1, 7], 3: [2, 6], 4: [3], 5: [4]}
print(set_a)
# {1, 2, 3, 4, 5}
For C++:
In case of using keyboard characters/numbers, an easier solution would be:
int key = cvWaitKey();
switch(key)
{
case ((int)('a')):
// do something if button 'a' is pressed
break;
case ((int)('h')):
// do something if button 'h' is pressed
break;
}
You can break up long lines with the caret ^
as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. (More on that below.)
Example:
copy file1.txt file2.txt
would be written as:
copy file1.txt^
file2.txt
It just looks for the presence of the .git directory in the solution folder. Delete that folder, possibly hidden, and Visual Studio will no longer consider it a git project.
You can just use nextLine();
as pause
import java.util.Scanner
//
//
Scanner scan = new Scanner(System.in);
void Read()
{
System.out.print("Press any key to continue . . . ");
scan.nextLine();
}
However any button you press except Enter
means you will have to press Enter after that but I found it better than scan.next();
This will get you count:
get-alias | measure
You can work with the result as with object:
$m = get-alias | measure
$m.Count
And if you would like to have aliases in some variable also, you can use Tee-Object:
$m = get-alias | tee -Variable aliases | measure
$m.Count
$aliases
Some more info on Measure-Object cmdlet is on Technet.
Do not confuse it with Measure-Command cmdlet which is for time measuring. (again on Technet)
UserDict from the Python standard library is designed for this purpose.
In my case, simply giving the user permissions on the database fixed it.
So Right click on the database -> Click Properties -> [left hand menu] Click Permissions -> and scroll down to Backup database -> Tick "Grant"
Adding this to your iframe might resolve the issue:
frameborder="0" seamless="seamless"
you can use sync storage that is easier to use than async storage. this library is great that uses async storage to save data asynchronously and uses memory to load and save data instantly synchronously, so we save data async to memory and use in app sync, so this is great.
import SyncStorage from 'sync-storage';
SyncStorage.set('foo', 'bar');
const result = SyncStorage.get('foo');
console.log(result); // 'bar'
As IE6 doesn't understand attribute selectors, you can combine a script only seen by IE6 (with conditional comments) and jQuery or IE7.js by Dean Edwards.
IE7(.js) is a JavaScript library to make Microsoft Internet Explorer behave like a standards-compliant browser. It fixes many HTML and CSS issues and makes transparent PNG work correctly under IE5 and IE6.
The choice of using classes or jQuery or IE7.js depends on your likes and dislikes and your other needs (maybe PNG-24 transparency throughout your site without having to rely on PNG-8 with complete transparency that fallbacks to 1-bit transparency on IE6 - only created by Fireworks and pngnq, etc)
You alread removed the active class from all the tabs but then you add the active class, again, to all the tabs. You should only add the active class to the currently selected tab like so http://jsfiddle.net/QFnRa/
$(".tab").removeClass("active");
$(this).addClass("active");
Try this instead, remove the SelectCommand property and SelectParameters:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:itematConnectionString %>">
Then in the code behind do this:
SqlDataSource1.SelectParameters.Add("userId", userId.ToString());
SqlDataSource1.SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"
While this worked for me, the following code also works:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:itematConnectionString %>"
SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"></asp:SqlDataSource>
SqlDataSource1.SelectParameters.Add("userid", DbType.Guid, userId.ToString());
Use return
operator:
function FUNCT {
if [ blah is false ]; then
return 1 # or return 0, or even you can omit the argument.
else
keep running the function
fi
}
python.exe -i
works but got issues in exiting from the interactive mode by sending "^Z" (CTRL+Z). So, seem better to use winpty python.exe
in Git Bash for Windows.
Use ~/bin
directory to make a wrap/reference file (like ~/bin/python
) which will be accessible everywhere (you may use different version reference like ~/bin/python37
).
Code inside the file:
#!/usr/bin/env bash
# maybe declare env vars here like
# export PYTHONHOME=/c/Users/%USERNAME%/.python/Python36
# export PATH="${PATH}:/c/Users/%USERNAME%/.python/Python36"
# replace %USERNAME%,
# or use "~" instead of "/c/Users/%USERNAME%" if it works
winpty /c/Users/%USERNAME%/.python/Python36/python.exe ${@}
I just don't like these "magic" aliases which you're always forgetting where it's coming from, and sometimes leads to issues in some cases.
~/bin/python
file and -i
parameter:#!/usr/bin/env bash
if [ -z "${@}" ]; then
# empty args, use interactive mode
/c/Users/%USERNAME%/.python/Python36/python.exe -i
else
/c/Users/%USERNAME%/.python/Python36/python.exe ${@}
fi
Converting your value in milliseconds to days is simply (MsValue / 86,400,000)
We can get 1/1/1970 as numeric value by DATE(1970,1,1)
= (MsValueCellReference / 86400000) + DATE(1970,1,1)
Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss
gives me a date and time of 19/04/2010 08:16:11
Even though the following will not satisfy this request (the function json_object_agg is not available in PostgreSQL 9.3), the following can be useful for anyone looking for a || operator for PostgreSQL 9.4, as implemented in the upcoming PostgreSQL 9.5:
CREATE OR REPLACE FUNCTION jsonb_merge(left JSONB, right JSONB)
RETURNS JSONB
AS $$
SELECT
CASE WHEN jsonb_typeof($1) = 'object' AND jsonb_typeof($2) = 'object' THEN
(SELECT json_object_agg(COALESCE(o.key, n.key), CASE WHEN n.key IS NOT NULL THEN n.value ELSE o.value END)::jsonb
FROM jsonb_each($1) o
FULL JOIN jsonb_each($2) n ON (n.key = o.key))
ELSE
(CASE WHEN jsonb_typeof($1) = 'array' THEN LEFT($1::text, -1) ELSE '['||$1::text END ||', '||
CASE WHEN jsonb_typeof($2) = 'array' THEN RIGHT($2::text, -1) ELSE $2::text||']' END)::jsonb
END
$$ LANGUAGE sql IMMUTABLE STRICT;
GRANT EXECUTE ON FUNCTION jsonb_merge(jsonb, jsonb) TO public;
CREATE OPERATOR || ( LEFTARG = jsonb, RIGHTARG = jsonb, PROCEDURE = jsonb_merge );
I divide the operators, for the purpose of teaching, into four categories:
It is fortunate, then, that most categories are represented in the question:
-> // Automatically imported method
||= // Syntactic sugar
++= // Syntactic sugar/composition or common method
<= // Common method
_._ // Typo, though it's probably based on Keyword/composition
:: // Common method
:+= // Common method
The exact meaning of most of these methods depend on the class that is defining them. For example, <=
on Int
means "less than or equal to". The first one, ->
, I'll give as example below. ::
is probably the method defined on List
(though it could be the object of the same name), and :+=
is probably the method defined on various Buffer
classes.
So, let's see them.
There are some symbols in Scala that are special. Two of them are considered proper keywords, while others are just "reserved". They are:
// Keywords
<- // Used on for-comprehensions, to separate pattern from generator
=> // Used for function types, function literals and import renaming
// Reserved
( ) // Delimit expressions and parameters
[ ] // Delimit type parameters
{ } // Delimit blocks
. // Method call and path separator
// /* */ // Comments
# // Used in type notations
: // Type ascription or context bounds
<: >: <% // Upper, lower and view bounds
<? <! // Start token for various XML elements
" """ // Strings
' // Indicate symbols and characters
@ // Annotations and variable binding on pattern matching
` // Denote constant or enable arbitrary identifiers
, // Parameter separator
; // Statement separator
_* // vararg expansion
_ // Many different meanings
These are all part of the language, and, as such, can be found in any text that properly describe the language, such as Scala Specification(PDF) itself.
The last one, the underscore, deserve a special description, because it is so widely used, and has so many different meanings. Here's a sample:
import scala._ // Wild card -- all of Scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]] // Higher kinded type parameter
def f(m: M[_]) // Existential type
_ + _ // Anonymous function placeholder parameter
m _ // Eta expansion of method into method value
m(_) // Partial function application
_ => 5 // Discarded parameter
case _ => // Wild card pattern -- matches anything
f(xs: _*) // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
I probably forgot some other meaning, though.
So, if you did not find the symbol you are looking for in the list above, then it must be a method, or part of one. But, often, you'll see some symbol and the documentation for the class will not have that method. When this happens, either you are looking at a composition of one or more methods with something else, or the method has been imported into scope, or is available through an imported implicit conversion.
These can still be found on ScalaDoc: you just have to know where to look for them. Or, failing that, look at the index (presently broken on 2.9.1, but available on nightly).
Every Scala code has three automatic imports:
// Not necessarily in this order
import _root_.java.lang._ // _root_ denotes an absolute path
import _root_.scala._
import _root_.scala.Predef._
The first two only make classes and singleton objects available. The third one contains all implicit conversions and imported methods, since Predef
is an object itself.
Looking inside Predef
quickly show some symbols:
class <:<
class =:=
object <%<
object =:=
Any other symbol will be made available through an implicit conversion. Just look at the methods tagged with implicit
that receive, as parameter, an object of type that is receiving the method. For example:
"a" -> 1 // Look for an implicit from String, AnyRef, Any or type parameter
In the above case, ->
is defined in the class ArrowAssoc
through the method any2ArrowAssoc
that takes an object of type A
, where A
is an unbounded type parameter to the same method.
So, many symbols are simply methods on a class. For instance, if you do
List(1, 2) ++ List(3, 4)
You'll find the method ++
right on the ScalaDoc for List. However, there's one convention that you must be aware when searching for methods. Methods ending in colon (:
) bind to the right instead of the left. In other words, while the above method call is equivalent to:
List(1, 2).++(List(3, 4))
If I had, instead 1 :: List(2, 3)
, that would be equivalent to:
List(2, 3).::(1)
So you need to look at the type found on the right when looking for methods ending in colon. Consider, for instance:
1 +: List(2, 3) :+ 4
The first method (+:
) binds to the right, and is found on List
. The second method (:+
) is just a normal method, and binds to the left -- again, on List
.
So, here's a few syntactic sugars that may hide a method:
class Example(arr: Array[Int] = Array.fill(5)(0)) {
def apply(n: Int) = arr(n)
def update(n: Int, v: Int) = arr(n) = v
def a = arr(0); def a_=(v: Int) = arr(0) = v
def b = arr(1); def b_=(v: Int) = arr(1) = v
def c = arr(2); def c_=(v: Int) = arr(2) = v
def d = arr(3); def d_=(v: Int) = arr(3) = v
def e = arr(4); def e_=(v: Int) = arr(4) = v
def +(v: Int) = new Example(arr map (_ + v))
def unapply(n: Int) = if (arr.indices contains n) Some(arr(n)) else None
}
val Ex = new Example // or var for the last example
println(Ex(0)) // calls apply(0)
Ex(0) = 2 // calls update(0, 2)
Ex.b = 3 // calls b_=(3)
// This requires Ex to be a "val"
val Ex(c) = 2 // calls unapply(2) and assigns result to c
// This requires Ex to be a "var"
Ex += 1 // substituted for Ex = Ex + 1
The last one is interesting, because any symbolic method can be combined to form an assignment-like method that way.
And, of course, there's various combinations that can appear in code:
(_+_) // An expression, or parameter, that is an anonymous function with
// two parameters, used exactly where the underscores appear, and
// which calls the "+" method on the first parameter passing the
// second parameter as argument.
The object keyword creates a new singleton type, which is like a class that only has a single named instance. If you’re familiar with Java, declaring an object in Scala is a lot like creating a new instance of an anonymous class.
Scala has no equivalent to Java’s static keyword, and an object is often used in Scala where you might use a class with static members in Java.
Try add it on AppDelegate.swift (inside application method):
UITabBar.appearance().tintColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0)
// For WHITE color:
UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
Example:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Tab bar icon selected color
UITabBar.appearance().tintColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0)
// For WHITE color: UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
return true
}
Example:
My english is so bad! I'm sorry! :-)
For me on RN 0.50.3 it's possible with this way:
<TextInput
autoFocus={true}
onSubmitEditing={() => {this.PasswordInputRef._root.focus()}}
/>
<TextInput ref={input => {this.PasswordInputRef = input}} />
You must see this.PasswordInputRef._root.focus()
The non-category plugin did not work for me.
For Multisite WordPress the following works:
\
;/%category%/%postname%/
.
This will display your url as www.domainname.com/categoryname/postname
;yourdoamainname/blog/
. Ignore it. If you save now the work you did in step 4 will be overwritten. This step of opening permalink page but not saving in needed to update the database.C is not object oriented programming (OOP) language. So you can not use properties in OOP. Eg. There is no .length property in C. So you need to use loops for your task.
It means that a process or script you have created is sending mail to an account on your local machine (for example, a mail server running on localhost application).
Manage this mail with these commands:
t <message list> type messages
n goto and type next message
e <message list> edit messages
f <message list> give head lines of messages
d <message list> delete messages
s <message list> file append messages to file
u <message list> undelete messages
R <message list> reply to message senders
r <message list> reply to message senders and all recipients
pre <message list> make messages go back to /var/mail
m <user list> mail to specific users
q quit, saving unresolved messages in mbox
x quit, do not remove system mailbox
h print out active message headers
! shell escape
cd [directory] chdir to directory or home if none given
A consists of integers, ranges of same, or user names separated by spaces. If omitted, Mail uses the last message typed.
A consists of user names or aliases separated by spaces. Aliases are defined in .mailrc in your home directory.
No, you cannot do that with CSS. That is the reason Microsoft initially introduced another, and maybe more practical box model. The box model that eventually won, makes it inpractical to mix percentages and units.
I don't think it is OK with you to express padding and border widths in percentage of the parent too.
Use a reg query and you will get an actual name: reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v ProductName
This would return "Windows 7 Professional", "Windows Server 2008 R2 Standard", etc. You can then combine with the ver command to get exact version.
To get milliseconds for current date.
Swift 4+:
func currentTimeInMilliSeconds()-> Int
{
let currentDate = Date()
let since1970 = currentDate.timeIntervalSince1970
return Int(since1970 * 1000)
}
The command should be the following script:
ilmerge myExe.exe Dll1.dll /target:winexe /targetplatform:"v4,c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\" /out:merged.exe /out:merged.exe
To get a definitive reason, you'd need to ask the designer(s) of that API.
But one possible reason is that the intent of a (hypothetical) nextChar
would not fit into the scanning model very well.
If nextChar()
to behaved like read()
on a Reader
and simply returned the next unconsumed character from the scanner, then it is behaving inconsistently with the other next<Type>
methods. These skip over delimiter characters before they attempt to parse a value.
If nextChar()
to behaved like (say) nextInt
then:
the delimiter skipping would be "unexpected" for some folks, and
there is the issue of whether it should accept a single "raw" character, or a sequence of digits that are the numeric representation of a char
, or maybe even support escaping or something1.
No matter what choice they made, some people wouldn't be happy. My guess is that the designers decided to stay away from the tarpit.
1 - Would vote strongly for the raw character approach ... but the point is that there are alternatives that need to be analysed, etc.
In order to make the existing primary key as auto_increment
, you may use:
ALTER TABLE table_name MODIFY id INT AUTO_INCREMENT;
var http = require('http');
http.createServer(function (req, res) {
}).listen(80, '127.0.0.1');
console.log('Server running at http://127.0.0.1:80/');
A simple possibility (if you'd rather avoid REs) is
' '.join(mystring.split())
The split and join perform the task you're explicitly asking about -- plus, they also do the extra one that you don't talk about but is seen in your example, removing trailing spaces;-).
Please note that in upcoming version of C# which is 8, the answers are not true.
All the reference types are non-nullable by default
and you can actually do the following:
public string? MyNullableString;
this.MyNullableString = null; //Valid
However,
public string MyNonNullableString;
this.MyNonNullableString = null; //Not Valid and you'll receive compiler warning.
The important thing here is to show the intent of your code. If the "intent" is that the reference type can be null, then mark it so otherwise assigning null value to non-nullable would result in compiler warning.
To the moderator who is deleting all the answers, don't do it. I strongly believe this answer adds value and deleting would simply keep someone from knowing what is right at the time. Since you have deleted all the answers, I'm re-posting answer here. The link that was sent regarding "duplicates" is simply an opening of some people and I do not think it is an official recommendation.
for( ; it != res.end();)
{
it = res.erase(it);
}
or, more general:
for( ; it != res.end();)
{
if (smth)
it = res.erase(it);
else
++it;
}
I have found in following way :
Go to https://itunesconnect.apple.com/ , sign in
Click "Resources and Help"
I use 'setAttribute' function:
<input type="text" id="example"> // Setup text field
<script type="text/javascript">
document.getElementById("example").setAttribute('value','My default value');
</script>
I'm not sure about this, but give it a shot.
In your strings.xml define:
<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>
In your layout:
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
android:entries="@array/array_name"
/>
I've heard this doesn't always work on the designer, but it compiles fine.