A simple way to use modals is with eModal!
Ex from github:
<script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
use eModal to display a modal for alert, ajax, prompt or confirm
// Display an alert modal with default title (Attention)
eModal.alert('You shall not pass!');
Here is a tested procedure that upgraded my database from local to utc time. The only input required to upgrade a database is to enter the number of minutes local time is offset from utc time into @Offset and if the timezone is subject to daylight savings adjustments by setting @ApplyDaylightSavings.
For example, US Central Time would enter @Offset=-360 and @ApplyDaylightSavings=1 for 6 hours and yes apply daylight savings adjustment.
Supporting Database Function
CREATE FUNCTION [dbo].[GetUtcDateTime](@LocalDateTime DATETIME, @Offset smallint, @ApplyDaylightSavings bit)
RETURNS DATETIME AS BEGIN
--====================================================
--Calculate the Offset Datetime
--====================================================
DECLARE @UtcDateTime AS DATETIME
SET @UtcDateTime = DATEADD(MINUTE, @Offset * -1, @LocalDateTime)
IF @ApplyDaylightSavings = 0 RETURN @UtcDateTime;
--====================================================
--Calculate the DST Offset for the UDT Datetime
--====================================================
DECLARE @Year as SMALLINT
DECLARE @DSTStartDate AS DATETIME
DECLARE @DSTEndDate AS DATETIME
--Get Year
SET @Year = YEAR(@LocalDateTime)
--Get First Possible DST StartDay
IF (@Year > 2006) SET @DSTStartDate = CAST(@Year AS CHAR(4)) + '-03-08 02:00:00'
ELSE SET @DSTStartDate = CAST(@Year AS CHAR(4)) + '-04-01 02:00:00'
--Get DST StartDate
WHILE (DATENAME(dw, @DSTStartDate) <> 'sunday') SET @DSTStartDate = DATEADD(day, 1,@DSTStartDate)
--Get First Possible DST EndDate
IF (@Year > 2006) SET @DSTEndDate = CAST(@Year AS CHAR(4)) + '-11-01 02:00:00'
ELSE SET @DSTEndDate = CAST(@Year AS CHAR(4)) + '-10-25 02:00:00'
--Get DST EndDate
WHILE (DATENAME(dw, @DSTEndDate) <> 'sunday') SET @DSTEndDate = DATEADD(day,1,@DSTEndDate)
--Finally add the DST Offset if needed
RETURN CASE WHEN @LocalDateTime BETWEEN @DSTStartDate AND @DSTEndDate THEN
DATEADD(MINUTE, -60, @UtcDateTime)
ELSE
@UtcDateTime
END
END
GO
Upgrade Script
begin try
begin transaction;
declare @sql nvarchar(max), @Offset smallint, @ApplyDaylightSavings bit;
set @Offset = -360; --US Central Time, -300 for US Eastern Time, -480 for US West Coast
set @ApplyDaylightSavings = 1; --1 for most US time zones except Arizona which doesn't observer daylight savings, 0 for most time zones outside the US
declare rs cursor for
select 'update [' + a.TABLE_SCHEMA + '].[' + a.TABLE_NAME + '] set [' + a.COLUMN_NAME + '] = dbo.GetUtcDateTime([' + a.COLUMN_NAME + '], ' + cast(@Offset as nvarchar) + ', ' + cast(@ApplyDaylightSavings as nvarchar) + ') ;'
from INFORMATION_SCHEMA.COLUMNS a
inner join INFORMATION_SCHEMA.TABLES b on a.TABLE_SCHEMA = b.TABLE_SCHEMA and a.TABLE_NAME = b.TABLE_NAME
where a.DATA_TYPE = 'datetime' and b.TABLE_TYPE = 'BASE TABLE' ;
open rs;
fetch next from rs into @sql;
while @@FETCH_STATUS = 0 begin
exec sp_executesql @sql;
print @sql;
fetch next from rs into @sql;
end
close rs;
deallocate rs;
commit transaction;
end try
begin catch
close rs;
deallocate rs;
declare @ErrorMessage nvarchar(max), @ErrorSeverity int, @ErrorState int;
select @ErrorMessage = ERROR_MESSAGE() + ' Line ' + cast(ERROR_LINE() as nvarchar(5)), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE();
rollback transaction;
raiserror (@ErrorMessage, @ErrorSeverity, @ErrorState);
end catch
You can read the lines and replace all special characters safely this way.
Keep in mind that if you use \\W
you will not replace underscores.
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine()){
System.out.println(scan.nextLine().replaceAll("[^a-zA-Z0-9]", ""));
}
You could try some sort of COALESCE trick, eg:
SELECT COALESCE( CASE WHEN condition1 THEN calculation1 ELSE NULL END, CASE WHEN condition2 THEN calculation2 ELSE NULL END, etc... )
If you are in a virtualenv you need to activate it before you can run ./manage.py 'command'
source path/to/your/virtualenv/bin/activate
if you config workon in .bash_profile or .bashrc
workon yourvirtualenvname
*please dont edit your manage.py file maybe works by isnt the correct way and could give you future errors
My immediate solution (since I couldn't find the ASP.NET worker process) was to give write (that is, Modify) permission to IIS_IUSRS. This worked. I seem to recall that in WinXP I had to specifically given the ASP.NET worker process write permission to accomplish this. Maybe my memory is faulty, but anyway...
@DraganRadivojevic wrote that he thought this was dangerous from a security viewpoint. I do not disagree, but since this was my workstation and not a network server, it seemed relatively safe. In any case, his answer is better and is what I finally settled on after chasing down a fail-path due to not specifying the correct domain for the AppPool user.
InputStream in = getResources().openRawResource(resourceName);
This will work correctly. Before that you have to create the xml file / text file in raw resource. Then it will be accessible.
Edit
Some times com.andriod.R will be imported if there is any error in layout file or image names. So You have to import package correctly, then only the raw file will be accessible.
All the above methods will work fine if your content-type is "application/-www-form-urlencoded". But if your content-type is "application/json" then you will have to do the following:
$params = json_decode(file_get_contents('php://input'), true); print_r($params);
Reason : See #7 in https://www.toptal.com/php/10-most-common-mistakes-php-programmers-make
The -n in the accept answers work. Here's another way in case you're inclined.
cat $filename | sed "${linenum}p;d";
This does the following:
Assuming that you're on SQL Server 2005 or greater, you can use a CTE with ROW_NUMBER():
SELECT *
FROM (SELECT ID, SKU, Product,
ROW_NUMBER() OVER (PARTITION BY PRODUCT ORDER BY ID) AS RowNumber
FROM MyTable
WHERE SKU LIKE 'FOO%') AS a
WHERE a.RowNumber = 1
(1) == can be be applied for both primitives and object types, but equals() method can be applied for only object types.
(2) == cannot be overridden for content comparison, but equals method can be overridden for content comparison(ex; String class, wrapper classes, collection classes).
(3) == gives incomparable types error when try to apply for heterogeneous types , where as equals method returns false.
Take a look at the Java 6 API under StringBuffer
String s = "sample";
String result = new StringBuffer(s).reverse().toString();
Updated.. I solved this issue by stating the charset on PDO connection as below:
"mysql:host=$host;dbname=$db;charset=utf8"
All data received was then in the correct charset for the rest of the code to use
I generally find the conditional command concatenation operators much more convenient than ERRORLEVEL.
yourCommand && (
echo yourCommand was successful
) || (
echo yourCommand failed
)
There is one complication you should be aware of. The error branch will fire if the last command in the success branch raises an error.
yourCommand && (
someCommandThatMayFail
) || (
echo This will fire if yourCommand or someCommandThatMayFail raises an error
)
The fix is to insert a harmless command that is guaranteed to succeed at the end of the success branch. I like to use (call )
, which does nothing except set the ERRORLEVEL to 0. There is a corollary (call)
that does nothing except set the ERRORLEVEL to 1.
yourCommand && (
someCommandThatMayFail
(call )
) || (
echo This can only fire if yourCommand raises an error
)
See Foolproof way to check for nonzero (error) return code in windows batch file for examples of the intricacies needed when using ERRORLEVEL to detect errors.
If the file does not exists, open(name,'r+')
will fail.
You can use open(name, 'w')
, which creates the file if the file does not exist, but it will truncate the existing file.
Alternatively, you can use open(name, 'a')
; this will create the file if the file does not exist, but will not truncate the existing file.
Thought I'd throw in some simplified examples, just so the options are all out there:
Unique number (could also put this into a method):
AtomicInteger threadNum = new AtomicInteger(0);
ExecutorService e = Executors.newSingleThreadExecutor(r -> new Thread(r, "my-name-" + threadNum.incrementAndGet()));
Unique number and "probably" unique name (if you're generating new Runnable objects). Useful if starting off the threads is within a method that gets called more than once, for instance:
AtomicInteger threadNum = new AtomicInteger(0);
ExecutorService e = Executors.newSingleThreadExecutor(r -> new Thread(r, "my-name-" + threadNum.incrementAndGet() + "-" + r.hashCode()));
If you really wanted a unique name each time you'd need a class with a static var (and could also add a static pool number prefix in there as well, see other answers).
and an equivalent in JDK < 8 (you don't need a new class for it, or could return a ThreadFactory out of a method):
Executors.newSingleThreadExecutor(new ThreadFactory() {
AtomicInteger threadCount = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "your-name-" + threadCount.getAndIncrement() + "-" + r.hashCode()); // could also use Integer.toHexString(r.hashCode()) for shorter
}
}));
And could make that into a method for the "you-name-" aspect as a variable. Or use a separate class with a constructor like the other answers all seem to.
For inserting at a particular position k
, you need to traverse the list till the position k-1
and then do the insert.
[You need not create a new node to traverse to that position as you did in your code] You should traverse from the head node.
I know this is an old thread, but it exactly matches what recently happened to me and I thought I'd document it here. The setup (in Docker) is as follows:
The symptom was a "502 Gateway Timeout" on the application login prompt. Examination of logs found:
POST
to /login
... and so .../login
request, and eventually reported a timeout.499
response, which of course means "the host died."/login
request did not appear at all(!) in the FPM server's logs!It turned out that the problem was a failure to connect to the database to verify the login. But how to figure that out turned out to be pure guesswork.
The complete absence of application traceback logs ... or even a record that the request had been received by FPM ... was a complete (and, devastating ...) surprise to me. Yes, the application is supposed to log failures, but in this case it looks like the FPM worker process died with a runtime error, leading to the 499
response from nginx. Now, this obviously is a problem in our application ... somewhere. But I wanted to record the particulars of what happened for the benefit of the next folks who face something like this.
If you want to select the type of console, you can write this in the file "keybinding.json" (this file can be found in the following path "File-> Preferences-> Keyboard Shortcuts") `
//with this you can select what type of console you want
{
"key": "ctrl+shift+t",
"command": "shellLauncher.launch"
},
//and this will help you quickly change console
{
"key": "ctrl+shift+j",
"command": "workbench.action.terminal.focusNext"
},
{
"key": "ctrl+shift+k",
"command": "workbench.action.terminal.focusPrevious"
}`
from the docs
Navbars may contain bits of text with the help of .navbar-text. This class adjusts vertical alignment and horizontal spacing for strings of text.
i applied the .navbar-text class to my <li>
element, so the result is
<li class="nav-item navbar-text">
this centers the links vertically with respect to my navbar-brand img
Apparently anonymous functions cannot be serialized.
Example
$function = function () {
return "ABC";
};
serialize($function); // would throw error
From your code you are using Closure:
$callback = function () // <---------------------- Issue
{
return 'ZendMail_' . microtime(true) . '.tmp';
};
Solution 1 : Replace with a normal function
Example
function emailCallback() {
return 'ZendMail_' . microtime(true) . '.tmp';
}
$callback = "emailCallback" ;
Solution 2 : Indirect method call by array variable
If you look at http://docs.mnkras.com/libraries_23rdparty_2_zend_2_mail_2_transport_2file_8php_source.html
public function __construct($options = null)
63 {
64 if ($options instanceof Zend_Config) {
65 $options = $options->toArray();
66 } elseif (!is_array($options)) {
67 $options = array();
68 }
69
70 // Making sure we have some defaults to work with
71 if (!isset($options['path'])) {
72 $options['path'] = sys_get_temp_dir();
73 }
74 if (!isset($options['callback'])) {
75 $options['callback'] = array($this, 'defaultCallback'); <- here
76 }
77
78 $this->setOptions($options);
79 }
You can use the same approach to send the callback
$callback = array($this,"aMethodInYourClass");
I tried all of the suggestions above and none of them worked for me, they changed the clientWidth and clientHeight not the actual width and height.
The jQuery docs for $().width and height methods says: "Note that .width("value") sets the content width of the box regardless of the value of the CSS box-sizing property."
The css approach did the same thing so I had to use the $().attr() methods instead.
_canvas.attr('width', 100);
_canvas.attr('height', 200);
I don't know is this affect me because I was trying to resize a element and it is some how different or not.
If it's always going to be an even LHS/RHS split, you can also use the partition
method that's built into strings. It returns a 3-tuple as (LHS, separator, RHS)
if the separator is found, and (original_string, '', '')
if the separator wasn't present:
>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')
>>> "shazam".partition("_")
('shazam', '', '')
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
I like the WMIC
and TASKLIST
tools but they are not available in home/basic editions of windows.Another way is to use QPROCESS
command available on almost every windows machine (for the ones that have terminal services - I think only win XP without SP2 , so practialy every windows machine):
@echo off
:check_process
setlocal
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running
set process_to_check=%~1
:: QPROCESS can display only the first 12 symbols of the running process
:: If other tool is used the line bellow could be deleted
set process_to_check=%process_to_check:~0,12%
QPROCESS * | find /i "%process_to_check%" >nul 2>&1 && (
echo process %process_to_check% is running
) || (
echo process %process_to_check% is not running
)
endlocal
QPROCESS
command is not so powerful as TASKLIST
and is limited in showing only 12 symbols of process name but should be taken into consideration if TASKLIST
is not available.
More simple usage where it uses the name if the process as an argument (the .exe
suffix is mandatory in this case where you pass the executable name):
@echo off
:check_process
setlocal
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running
:: .exe suffix is mandatory
set "process_to_check=%~1"
QPROCESS "%process_to_check%" >nul 2>&1 && (
echo process %process_to_check% is running
) || (
echo process %process_to_check% is not running
)
endlocal
The difference between two ways of QPROCESS
usage is that the QPROCESS *
will list all processes while QPROCESS some.exe
will filter only the processes for the current user.
Using WMI
objects through windows script host exe instead of WMIC
is also an option.It should on run also on every windows machine (excluding the ones where the WSH is turned off but this is a rare case).Here bat file that lists all processes through WMI classes and can be used instead of QPROCESS
in the script above (it is a jscript/bat hybrid and should be saved as .bat
):
@if (@X)==(@Y) @end /* JSCRIPT COMMENT **
@echo off
cscript //E:JScript //nologo "%~f0"
exit /b
************** end of JSCRIPT COMMENT **/
var winmgmts = GetObject("winmgmts:\\\\.\\root\\cimv2");
var colProcess = winmgmts.ExecQuery("Select * from Win32_Process");
var processes = new Enumerator(colProcess);
for (;!processes.atEnd();processes.moveNext()) {
var process=processes.item();
WScript.Echo( process.processID + " " + process.Name );
}
And a modification that will check if a process is running:
@if (@X)==(@Y) @end /* JSCRIPT COMMENT **
@echo off
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running
set process_to_check=%~1
cscript //E:JScript //nologo "%~f0" | find /i "%process_to_check%" >nul 2>&1 && (
echo process %process_to_check% is running
) || (
echo process %process_to_check% is not running
)
exit /b
************** end of JSCRIPT COMMENT **/
var winmgmts = GetObject("winmgmts:\\\\.\\root\\cimv2");
var colProcess = winmgmts.ExecQuery("Select * from Win32_Process");
var processes = new Enumerator(colProcess);
for (;!processes.atEnd();processes.moveNext()) {
var process=processes.item();
WScript.Echo( process.processID + " " + process.Name );
}
The two options could be used on machines that have no TASKLIST
.
The ultimate technique is using MSHTA
. This will run on every windows machine from XP and above and does not depend on windows script host settings. the call of MSHTA
could reduce a little bit the performance though (again should be saved as bat):
@if (@X)==(@Y) @end /* JSCRIPT COMMENT **
@echo off
setlocal
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running
set process_to_check=%~1
mshta "about:<script language='javascript' src='file://%~dpnxf0'></script>" | find /i "%process_to_check%" >nul 2>&1 && (
echo process %process_to_check% is running
) || (
echo process %process_to_check% is not running
)
endlocal
exit /b
************** end of JSCRIPT COMMENT **/
var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
var winmgmts = GetObject("winmgmts:\\\\.\\root\\cimv2");
var colProcess = winmgmts.ExecQuery("Select * from Win32_Process");
var processes = new Enumerator(colProcess);
for (;!processes.atEnd();processes.moveNext()) {
var process=processes.item();
fso.Write( process.processID + " " + process.Name + "\n");
}
close();
Use for on refresh event
window.onbeforeunload = function(e) {
return 'Dialog text here.';
};
And
$(window).unload(function() {
alert('Handler for .unload() called.');
});
If you change from using a lambda with one argument to a function with one argument, you will get this error.
For example:
You had:
foobar = lambda do |baz|
puts baz
end
and you changed the definition to
def foobar(baz)
puts baz
end
And you left your invocation as:
foobar.call(baz)
And then you got the message
ArgumentError: wrong number of arguments (0 for 1)
when you really meant:
foobar(baz)
Be very careful with the Excel MOD(a,b) function and the VBA a Mod b operator. Excel returns a floating point result and VBA an integer.
In Excel =Mod(90.123,90) returns 0.123000000000005 instead of 0.123 In VBA 90.123 Mod 90 returns 0
They are certainly not equivalent!
Equivalent are: In Excel: =Round(Mod(90.123,90),3) returning 0.123 and In VBA: ((90.123 * 1000) Mod 90000)/1000 returning also 0.123
I feel the pain!
Although this is an old post, I think what one really needs to understand, is not the "move this to that" approach but that the answer involves using the side-effect of the recursion.
A invaluable help to me was the "The Little Schemer" which teaches one to think and write recursive functions.
However, this teaches the reader to use the results of the returned result in the next recursive call.
In the Tower of Hanoi, the answer is not in the returned result per se, but in the observation of the returned result.
The magic occurs in the succesive rearrangment of the function parameters.
Yes the problem is really in three parts:
In Scheme:
(define (th n a b c)
(if (zero? n) 'done
(begin
(th (- n 1) a c b)
(display (list a c))
(newline)
(th (- n 1) b a c))))
(th 5 'source 'spare 'destination)
However it is the displaying of the function parameters which is the solution to the problem and crucially understanding the double tree like structure of the calls.
The solution also conveys the power of proof by induction
and a warm glow to all programmers who have wrestled with conventional control structures.
Incidently, to solve the problem by hand is quite satisfying.
Best done by always holding the top disc with the same hand and always moving that hand in the same direction.
The final number of moves for n
discs is 2^n - 1
the move n disc to destination
is halfway through the process.
Lastly, it is funny how explaining a problem to a colleague, your wife/husband or even the dog (even it they not listening) can cement enlightenment.
There are some great examples in here, but I couldn't get this to work in all cases when also dealing with multiple lines of text (text wrapping). To finally get it to work I combined a couple of the techniques:
I used Jesse Crossen example above. However, I fixed a text height issue and I added the ability to specify a horizontal text margin. The margin is useful when allowing text to wrap so it doesn't hit the edge of the button:
// the space between the image and text
CGFloat spacing = 10.0;
float textMargin = 6;
// get the size of the elements here for readability
CGSize imageSize = picImage.size;
CGSize titleSize = button.titleLabel.frame.size;
CGFloat totalHeight = (imageSize.height + titleSize.height + spacing); // get the height they will take up as a unit
// lower the text and push it left to center it
button.titleEdgeInsets = UIEdgeInsetsMake( 0.0, -imageSize.width +textMargin, - (totalHeight - titleSize.height), +textMargin ); // top, left, bottom, right
// the text width might have changed (in case it was shortened before due to
// lack of space and isn't anymore now), so we get the frame size again
titleSize = button.titleLabel.bounds.size;
button.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), 0.0, 0.0, -titleSize.width ); // top, left, bottom, right
Make sure you setup the text label to wrap
button.titleLabel.numberOfLines = 2; button.titleLabel.lineBreakMode = UILineBreakModeWordWrap; button.titleLabel.textAlignment = UITextAlignmentCenter;
This will mostly work now. However, I had some buttons that wouldn't render their image correctly. The image was either shifted to far to the right or left (it wasn't centered). So I used an UIButton layout override technique to force the imageView to be centered.
@interface CategoryButton : UIButton @end @implementation CategoryButton - (void)layoutSubviews { // Allow default layout, then center imageView [super layoutSubviews]; UIImageView *imageView = [self imageView]; CGRect imageFrame = imageView.frame; imageFrame.origin.x = (int)((self.frame.size.width - imageFrame.size.width)/ 2); imageView.frame = imageFrame; } @end
In addition to answer of @gjha:
inline std::string ltrim_copy(const std::string& str)
{
auto it = std::find_if(str.cbegin(), str.cend(),
[](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
return std::string(it, str.cend());
}
inline std::string rtrim_copy(const std::string& str)
{
auto it = std::find_if(str.crbegin(), str.crend(),
[](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
return it == str.crend() ? std::string() : std::string(str.cbegin(), ++it.base());
}
inline std::string trim_copy(const std::string& str)
{
auto it1 = std::find_if(str.cbegin(), str.cend(),
[](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
if (it1 == str.cend()) {
return std::string();
}
auto it2 = std::find_if(str.crbegin(), str.crend(),
[](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
return it2 == str.crend() ? std::string(it1, str.cend()) : std::string(it1, ++it2.base());
}
Super simple approach:
R.java
in the build/generated directoryR.java
to the newly created package. Done!
To get it at any time, you can do SELECT MAX(Id) FROM Customers
.
In the procedure you add it in, however, you can also make use of SCOPE_IDENTITY
-- to get the id last added by that procedure.
This is safer, because it will guarantee you get your Id
--just in case others are being added to the database at the same time.
In angular using material design sidenav I had to use the following:
let ele = document.getElementsByClassName('md-sidenav-content');
let eleArray = <Element[]>Array.prototype.slice.call(ele);
eleArray.map( val => {
val.scrollTop = val.scrollHeight;
});
This one worked for me, in startup.bat
the following line needs to be added if it doesn't exist set JAVA_OPTS
with the value -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256
. The full line:
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256
SELECT *
FROM my_table
WHERE substr(my_field,1,5) = "abcde";
Agree with Gray, as you may need your pattern to have both litrals (\[, \]) and meta-characters ([, ]). so with some utility you should be able to escape all character first and then you can add meta-characters you want to add on same pattern.
d = {"name":"interpolator",
"children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)
Of course, it's unlikely that the order will be exactly preserved ... But that's just the nature of dictionaries ...
This error occurs because of invalid mapping configuration. You should check where you set .Mappings for your session factory. Basically search for ".Mappings(" in your project and make sure you specified correct entity class in below line.
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<YourEntityClassName>())
If you disable the Program Compatibility Mode and the problem persists, copy the content of ISO to a local path and try install with a simple double click
Please take a look here:
1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.
2) Step-by-step tutorial how to use serial ports on windows
3) You can use this literally on MinGW
Here's some very, very simple code (without any error handling or settings):
#include <windows.h>
/* ... */
// Open serial port
HANDLE serialHandle;
serialHandle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);
GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);
// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;
SetCommTimeouts(serialHandle, &timeout);
Now you can use WriteFile()
/ ReadFile()
to write / read bytes.
Don't forget to close your connection:
CloseHandle(serialHandle);
You are not creating datetime index properly,
format = '%Y-%m-%d %H:%M:%S'
df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'], format=format)
df = df.set_index(pd.DatetimeIndex(df['Datetime']))
@jovi all you need to do is add .babelrc file like this:
{
"plugins": [
"transform-strict-mode",
"transform-es2015-modules-commonjs",
"transform-es2015-spread",
"transform-es2015-destructuring",
"transform-es2015-parameters"
]
}
and install these plugins as devdependences with npm.
then try babel-node ***.js again. hope this can help you.
There is this extensions that adds an event listener to attribute changes.
Usage:
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript"
src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>
Bind attrchange handler function to selected elements
$(selector).attrchange({
trackValues: true, /* Default to false, if set to true the event object is
updated with old and new value.*/
callback: function (event) {
//event - event object
//event.attributeName - Name of the attribute modified
//event.oldValue - Previous value of the modified attribute
//event.newValue - New value of the modified attribute
//Triggered when the selected elements attribute is added/updated/removed
}
});
You can use general compound drawable implementation, but if you need to define a size of drawable use this library:
https://github.com/a-tolstykh/textview-rich-drawable
Here is a small example of usage:
<com.tolstykh.textviewrichdrawable.TextViewRichDrawable
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Some text"
app:compoundDrawableHeight="24dp"
app:compoundDrawableWidth="24dp" />
well, you can try the javascript plugin which can monitor the browser connection in real time and notifies the user if internet or the browsers connection with the internet went down.
Wiremonkey Javascript plugin and the demo you can find here
There are 2 jQuery functions that you'll want to use here.
1) click
. This will take an anonymous function as it's sole parameter, and will execute it when the element is clicked.
2) html
. This will take an html string as it's sole parameter, and will replace the contents of your element with the html provided.
So, in your case, you'll want to do the following:
$('#content-container a').click(function(e){
$(this).parent().html('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
If you only want to add content to your div, rather than replacing everything in it, you should use append
:
$('#content-container a').click(function(e){
$(this).parent().append('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
If you want the new added links to also add new content when clicked, you should use event delegation:
$('#content-container').on('click', 'a', function(e){
$(this).parent().append('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
If you are on Linux you may not have docker-machine
installed since it is only installed by default on Windows and Mac computers.
If so you will need to got to: https://docs.docker.com/machine/install-machine/ to find instructions for how to install it on your version of Linux.
After installing, retry running docker-compose up
before trying anything listed above.
Hope this helps someone. This worked for my devilbox installation in Fedora 25.
As the chosen answer is pretty old, and things changed, here is the new procedure, if you use 64 bits Notepad++. 64 bits version does not come with Plugin Manager nor NppExport. All details provided here.
To resume quickly, Plugin Manager is no longer develloped and NppExport can be found just here.
You should initialize your variables outside the while loop. Outside the while loop, they currently have no scope. You are just relying on the good graces of php to let the values carry over outside the loop
$hn = "";
$pid = "";
$datereg = "";
$prefix = "";
$fname = "";
$lname = "";
$age = "";
$sex = "";
while (...){}
alternatively, it looks like you are just expecting a single row back. so you could just say
$row = pg_fetch_array($result);
if(!row) {
return array();
}
$hn = $row["patient_hn"];
$pid = $row["patient_id"];
$datereg = $row["patient_date_register"];
$prefix = $row["patient_prefix"];
$fname = $row["patient_fname"];
$lname = $row["patient_lname"];
$age = $row["patient_age"];
$sex = $row["patient_sex"];
return array($hn,$pid,$datereg,$prefix,$fname,$lname,$age,$sex) ;
Follow this steps:
-Build
-Generate Signed Apk
-Create new
Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)
I was going through some details related to tuple
and list
, and what I understood is:
Heterogeneous
collection data typeSo for appending new item to a tuple, need to cast it to list
, and do append()
operation on it, then again cast it back to tuple.
But personally what I felt about the Question is, if Tuples are supposed to be finite, fixed length items and if we are using those data types in our application logics then there should not be a scenario to appending new items OR updating an item value in it. So instead of list of tuples it should be list of list itself, Am I right on this?
I had the same problem. Debugging does not work with the stuff that comes with the OpenCV executable. you have to build your own binarys.
Then enable Microsoft Symbol Servers in Debug->options and settings->debug->symbols
<img src="/images/yourfile.png">
Store your files in public/images directory.
You can use Excel Automation (it is basically a COM Base stuff) e.g:
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("1.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JsonUtils {
public static Map<String, Object> jsonToMap(JSONObject json) {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != null) {
retMap = toMap(json);
}
return retMap;
}
public static Map<String, Object> toMap(JSONObject object) {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keySet().iterator();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.size(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
You need to edit your my.cnf
file and make sure you have the port set as in the following line:
port = 3360
Then restart your MySQL service and you should be good to go. There is no query you can run to make this change because the port
is not a dynamic variable (q.v. here for MySQL documentation showing a table of all system variables).
double.Parse("-"); raises an exception, while double.TryParse("-", out parsed); parses to 0 so I guess TryParse does more complex conversions.
in my case, i was sure that the action is correct, but i was passing wrong URL, i passed the website link without the http:// in it's beginning, so it caused the same issue, here is my manifest (part of it)
<activity
android:name=".MyBrowser"
android:label="MyBrowser Activity" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="com.dsociety.activities.MyBrowser" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>
when i code the following, the same Exception is thrown at run time :
Intent intent = new Intent();
intent.setAction("com.dsociety.activities.MyBrowser");
intent.setData(Uri.parse("www.google.com")); // should be http://www.google.com
startActivity(intent);
I use both <strong> and <b>, actually, for exactly the reasons mentioned in this thread of responses. There are times when bold-facing some text simply looks better, but it isn't, necessarily, semantically more important than the rest of the sentence. Here's an example from a page I'm working on right now:
"Retrieves <strong>all</strong> books about <b>lacrosse</b>."
In that sentence, the word "all" is very important, and "lacrosse" less so--I merely wanted it bold because it represents a search term, so I wanted some visual separation. If you're viewing the page with a screen reader, I really don't think it needs to go out of the way to emphasize the word "lacrosse".
I would tend to imagine that most web developers use one of the other, but both are fine--<b> is most definitely not deprecated, as some people have claimed. For me, it's just a fine line between visual appeal and meaning.
Its a base64url encode you can try out, its just extension of joeshmo's code above.
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
import os
os.system('pip install requests')
I tried above for temporary solution instead of changing docker file. Hope these might be useful to some
On your model class decorate that property with [Required]
attribute. I.e.:
[Required]
public string ShortName {get; set;}
You can download the gradle you want from Gradle Service by reading the gradle-wrapper.properties.Download it ,unpack it where you like and then change your grandle configuration use local not the recommended.
Try:
ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 tar xvfz
Then Try:
ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 rm
This will untar all .tar.gz files in the current directory and then delete all the .tar.gz files. If you want an explanation, the "|" takes the stdout of the command before it, and uses that as the stdin of the command after it. Use "man command" w/o the quotes to figure out what those commands and arguments do. Or, you can research online.
No, currently you can not. It was only possible with the old recaptcha, but I'm sure you will be able to do that in the future.
I have no solution but a suggestion. I had the same problem, so I centered the recaptcha div
(margin: 0 auto;display: table
), I think it looks much better than a left-aligned div.
In .net 4.0 Microsoft removed the ability to add DLLs to the Assembly simply by dragging and dropping.
Instead you need to use gacutil.exe, or create an installer to do it. Microsoft actually doesn’t recommend using gacutil, but I went that route anyway.
To use gacutil on a development machine go to:
Start -> programs -> Microsoft Visual studio 2010 -> Visual Studio Tools -> Visual Studio Command Prompt (2010)
Then use these commands to uninstall and Reinstall respectively. Note I did NOT include .dll
in the uninstall command.
gacutil /u myDLL
gacutil /i "C:\Program Files\Custom\myDLL.dll"
To use Gacutil on a non-development machine you will have to copy the executable and config file from your dev machine to the production machine. It looks like there are a few different versions of Gacutil. The one that worked for me, I found here:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\gacutil.exe
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\gacutil.exe.config
Copy the files here or to the appropriate .net folder;
C:\Windows\Microsoft.NET\Framework\v4.0.30319
Then use these commands to uninstall and reinstall respectively
"C:\Users\BHJeremy\Desktop\Installing to the Gac in .net 4.0\gacutil.exe" /u "myDLL"
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\gacutil.exe" /i "C:\Program Files\Custom\myDLL.dll"
Here is the XSLT function which will work similar to the String.Replace() function of C#.
This template has the 3 Parameters as below
text :- your main string
replace :- the string which you want to replace
by :- the string which will reply by new string
Below are the Template
<xsl:template name="string-replace-all">
<xsl:param name="text" />
<xsl:param name="replace" />
<xsl:param name="by" />
<xsl:choose>
<xsl:when test="contains($text, $replace)">
<xsl:value-of select="substring-before($text,$replace)" />
<xsl:value-of select="$by" />
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="substring-after($text,$replace)" />
<xsl:with-param name="replace" select="$replace" />
<xsl:with-param name="by" select="$by" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Below sample shows how to call it
<xsl:variable name="myVariable ">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="'This is a {old} text'" />
<xsl:with-param name="replace" select="'{old}'" />
<xsl:with-param name="by" select="'New'" />
</xsl:call-template>
</xsl:variable>
You can also refer the below URL for the details.
There is no solution to this problem. As of IE11 on Windows 8, Microsoft no longer allows ActiveX plugins to run in its browser space. There is absolutely nothing that a third party developer can do about it.
A similar thing has recently happened with the Chrome browser which no longer supports NPAPI plugins. Instead Chrome only supports PPAPI plugins which are useless for system level tasks once performed by NPAPI plugins.
So developers needing browser support for system interactive plugins can only recommend either the Firefox browser or the ASPS web browser.
public static void main(String[] args) throws IOException {
String filePath = "/Users/myXml/VH181.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
printElement(doc);
System.out.println("XML file updated successfully");
} catch (SAXException | ParserConfigurationException e1) {
e1.printStackTrace();
}
}
private static void printElement(Document someNode) {
NodeList nodeList = someNode.getElementsByTagName("choiceInteraction");
for(int z=0,size= nodeList.getLength();z<size; z++) {
String Value = nodeList.item(z).getAttributes().getNamedItem("id").getNodeValue();
System.out.println("Choice Interaction Id:"+Value);
}
}
we Can try this code using method
Echo the session object as json. I like json because I have a browser extension that nicely formats json.
session_start();
echo json_encode($_SESSION);
To get support for C++14 in Eclipse Luna, you could do these steps:
C++ General -> Preprocessor Include -> Providers -> CDT Cross GCC Built-in Compiler Settings
, add "-std=c++14"C++ Build -> Settings -> Cross G++ Compiler -> Miscellaneous
, add "-std=c++14"Reindex your project and eventually restart Eclipse. It should work as expected.
Use req.app
, req.app.get('somekey')
The application variable created by calling express()
is set on the request and response objects.
Let me explain a little more by my example.
Task: correct info, where abiturients (students about to leave secondary school) have submitted applications to university earlier, than they got school certificates (yes, they got certificates earlier, than they were issued (by certificate date specified). So, we will increase application submit date to fit certificate issue date.
Thus. next MySQL-like statement:
UPDATE applications a
JOIN (
SELECT ap.id, ab.certificate_issued_at
FROM abiturients ab
JOIN applications ap
ON ab.id = ap.abiturient_id
WHERE ap.documents_taken_at::date < ab.certificate_issued_at
) b
ON a.id = b.id
SET a.documents_taken_at = b.certificate_issued_at;
Becomes PostgreSQL-like in such a way
UPDATE applications a
SET documents_taken_at = b.certificate_issued_at -- we can reference joined table here
FROM abiturients b -- joined table
WHERE
a.abiturient_id = b.id AND -- JOIN ON clause
a.documents_taken_at::date < b.certificate_issued_at -- Subquery WHERE
As you can see, original subquery JOIN
's ON
clause have become one of WHERE
conditions, which is conjucted by AND
with others, which have been moved from subquery with no changes. And there is no more need to JOIN
table with itself (as it was in subquery).
What about this:
otherfunction(thing_collection, thing)
Rather than expose something so implementation-dependent like a list index in a function interface, pass the collection and the thing and let otherfunction deal with the "test for membership" issues. If otherfunction is written to be collection-type-agnostic, then it would probably start with:
if thing in thing_collection:
... proceed with operation on thing
which will work if thing_collection is a list, tuple, set, or dict.
This is possibly clearer than:
if thing_index != MAGIC_VALUE_INDICATING_NOT_A_MEMBER:
which is the code you already have in otherfunction.
You can check if it can be converted to decimal. If yes, then its a number
from decimal import Decimal
def is_number(value):
try:
value = Decimal(value)
return True
except:
return False
print is_number(None) // False
print is_number(0) // True
print is_number(2.3) // True
print is_number('2.3') // True (caveat!)
A different way
$("#inline_content input[name='type']").change(function () {
if ($(this).val() == "walk_in" && $(this).is(":checked")) {
$('#select-table > .roomNumber').attr('enabled', false);
}
});
Demo - http://jsfiddle.net/cB6xV/
See the Parameter Expansion section in the Bash man
page. A[@]
returns the contents of the array, :1:2
takes a slice of length 2, starting at index 1.
A=( foo bar "a b c" 42 )
B=("${A[@]:1:2}")
C=("${A[@]:1}") # slice to the end of the array
echo "${B[@]}" # bar a b c
echo "${B[1]}" # a b c
echo "${C[@]}" # bar a b c 42
echo "${C[@]: -2:2}" # a b c 42 # The space before the - is necesssary
Note that the fact that "a b c" is one array element (and that it contains an extra space) is preserved.
I had a similar issue and found that it was much simpler to to get rid of the Excel files as soon as possible. As part of the first steps in my package I used Powershell to extract the data out of the Excel files into CSV files. My own Excel files were simple but here
Extract and convert all Excel worksheets into CSV files using PowerShell
is an excellent article by Tim Smith on extracting data from multiple Excel files and/or multiple sheets.
Once the Excel files have been converted to CSV the data import is much less complicated.
JavaScript doesn't have associate arrays. You need to use Objects instead:
var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);?
To get value you can use now different ways:
console.log(obj.name);?
console.log(obj[name]);?
console.log(obj["name"]);?
//you need to import
QuartzCore/QuartzCore.h
& then for ImageView in border
[imageView.layer setBorderColor: [[UIColor blackColor] CGColor]];
[imageView.layer setBorderWidth: 2.0];
[imageView.layer setCornerRadius: 5.0];
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }
and Remove a "{"..,
strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));
DeserializeObject..,
optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);
You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:
SELECT TO_CHAR(
TO_DATE('15/August/2009,4:30 PM'
,'DD/Month/YYYY,HH:MI AM')
,'DD-MM-YYYY')
FROM DUAL;
15-08-2009
For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:
SELECT TO_CHAR(
TO_DATE(MYDATESTRING
,'DD/Month/YYYY,HH:MI AM')
,'DD-MM-YYYY')
FROM MYTABLE;
I've made a very simple zero config category to hide all back button titles through out app you can check it out here. This question already has accepted answer, but for others it can be helpful.
EDIT:
.h file
#import <UIKit/UIKit.h>
@interface UINavigationController (HideBackTitle)
extern void PJSwizzleMethod(Class cls, SEL originalSelector, SEL swizzledSelector);
@end
.m file
#import "UINavigationController+HideBackTitle.h"
#import <objc/runtime.h>
@implementation UINavigationController (HideBackTitle)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
PJSwizzleMethod([self class],
@selector(pushViewController:animated:),
@selector(pj_pushViewController:animated:));
});
}
- (void)pj_pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
UIViewController *disappearingViewController = self.viewControllers.lastObject;
if (disappearingViewController) {
disappearingViewController.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}
if (!disappearingViewController) {
return [self pj_pushViewController:viewController animated:animated];
}
return [self pj_pushViewController:viewController animated:animated];
}
@end
void PJSwizzleMethod(Class cls, SEL originalSelector, SEL swizzledSelector)
{
Method originalMethod = class_getInstanceMethod(cls, originalSelector);
Method swizzledMethod = class_getInstanceMethod(cls, swizzledSelector);
BOOL didAddMethod =
class_addMethod(cls,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(cls,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
Set back button item title as empty String.
[self.navigationController.navigationBar.backItem setTitle:@""];
background.xml in drawable folder.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke
android:width="3dp"
android:color="#0FECFF" />
//specify gradient
<gradient
android:startColor="#ffffffff"
android:endColor="#110000FF"
android:angle="90"/>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:orientation="vertical"
android:layout_marginBottom="10dp"
android:background="@drawable/background">
This answer might be late but I would like to mention few things when your Activity
dependent on AsyncTask
. That would help you in prevent crashes and memory management. As already mentioned in above answers go with interface
, we also say them callbacks. They will work as an informer, but never ever send strong reference of Activity
or interface
always use weak reference in those cases.
Please refer to below screenshot to findout how that can cause issues.
As you can see if we started AsyncTask
with a strong reference then there is no guarantee that our Activity
/Fragment
will be alive till we get data, so it would be better to use WeakReference
in those cases and that will also help in memory management as we will never hold the strong reference of our Activity
then it will be eligible for garbage collection after its distortion.
Check below code snippet to find out how to use awesome WeakReference -
MyTaskInformer.java
Interface which will work as an informer.
public interface MyTaskInformer {
void onTaskDone(String output);
}
MySmallAsyncTask.java
AsyncTask to do long running task, which will use WeakReference
.
public class MySmallAsyncTask extends AsyncTask<String, Void, String> {
// ***** Hold weak reference *****
private WeakReference<MyTaskInformer> mCallBack;
public MySmallAsyncTask(MyTaskInformer callback) {
this.mCallBack = new WeakReference<>(callback);
}
@Override
protected String doInBackground(String... params) {
// Here do whatever your task is like reading/writing file
// or read data from your server or any other heavy task
// Let us suppose here you get response, just return it
final String output = "Any out, mine is just demo output";
// Return it from here to post execute
return output;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// Here you can't guarantee that Activity/Fragment is alive who started this AsyncTask
// Make sure your caller is active
final MyTaskInformer callBack = mCallBack.get();
if(callBack != null) {
callBack.onTaskDone(s);
}
}
}
MainActivity.java
This class is used to start my AsyncTask
implement interface
on this class and override
this mandatory method.
public class MainActivity extends Activity implements MyTaskInformer {
private TextView mMyTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMyTextView = (TextView) findViewById(R.id.tv_text_view);
// Start your AsyncTask and pass reference of MyTaskInformer in constructor
new MySmallAsyncTask(this).execute();
}
@Override
public void onTaskDone(String output) {
// Here you will receive output only if your Activity is alive.
// no need to add checks like if(!isFinishing())
mMyTextView.setText(output);
}
}
I had the same problem but solved it when I realized that I didn't compile it with the correct casing. You may have been doing
javac Weatherarray.java
when it should have been
javac WeatherArray.java
I found this solution:
This query select last not null value for each column.
Example
If you have a table:
id|title|body
1 |t1 |b1
2 |NULL |b2
3 |t3 |NULL
you get:
title|body
t3 |b2
Query
SELECT DISTINCT (
SELECT title
FROM test
WHERE title IS NOT NULL
ORDER BY id DESC
LIMIT 1
) title, (
SELECT body
FROM test
WHERE body IS NOT NULL
ORDER BY id DESC
LIMIT 1
) body
FROM test
I hope help you.
just in case you are using a remote access and want to dump all database data, you can use:
pg_dump -a -h your_host -U your_user -W -Fc your_database > DATA.dump
it will create a dump with all database data and use
pg_restore -a -h your_host -U your_user -W -Fc your_database < DATA.dump
to insert the same data in your data base considering you have the same structure
Go to properties of your project ( with Alt+Enter or righ-click )
check on Apache Tomcat v7.0 under Targeted Runtime and it works.
You should always use the resource manager and not read files directly to ensure globalization is taken into account.
using System.Collections;
using System.Globalization;
using System.Resources;
...
/* Reference to your resources class -- may be named differently in your case */
ResourceManager MyResourceClass =
new ResourceManager(typeof(Resources));
ResourceSet resourceSet =
MyResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
string resourceKey = entry.Key.ToString();
object resource = entry.Value;
}
I wrote a DateTextField component.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class DateTextField extends JTextField {
private static String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
private static final int DIALOG_WIDTH = 200;
private static final int DIALOG_HEIGHT = 200;
private SimpleDateFormat dateFormat;
private DatePanel datePanel = null;
private JDialog dateDialog = null;
public DateTextField() {
this(new Date());
}
public DateTextField(String dateFormatPattern, Date date) {
this(date);
DEFAULT_DATE_FORMAT = dateFormatPattern;
}
public DateTextField(Date date) {
setDate(date);
setEditable(false);
setCursor(new Cursor(Cursor.HAND_CURSOR));
addListeners();
}
private void addListeners() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent paramMouseEvent) {
if (datePanel == null) {
datePanel = new DatePanel();
}
Point point = getLocationOnScreen();
point.y = point.y + 30;
showDateDialog(datePanel, point);
}
});
}
private void showDateDialog(DatePanel dateChooser, Point position) {
Frame owner = (Frame) SwingUtilities
.getWindowAncestor(DateTextField.this);
if (dateDialog == null || dateDialog.getOwner() != owner) {
dateDialog = createDateDialog(owner, dateChooser);
}
dateDialog.setLocation(getAppropriateLocation(owner, position));
dateDialog.setVisible(true);
}
private JDialog createDateDialog(Frame owner, JPanel contentPanel) {
JDialog dialog = new JDialog(owner, "Date Selected", true);
dialog.setUndecorated(true);
dialog.getContentPane().add(contentPanel, BorderLayout.CENTER);
dialog.pack();
dialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
return dialog;
}
private Point getAppropriateLocation(Frame owner, Point position) {
Point result = new Point(position);
Point p = owner.getLocation();
int offsetX = (position.x + DIALOG_WIDTH) - (p.x + owner.getWidth());
int offsetY = (position.y + DIALOG_HEIGHT) - (p.y + owner.getHeight());
if (offsetX > 0) {
result.x -= offsetX;
}
if (offsetY > 0) {
result.y -= offsetY;
}
return result;
}
private SimpleDateFormat getDefaultDateFormat() {
if (dateFormat == null) {
dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
}
return dateFormat;
}
public void setText(Date date) {
setDate(date);
}
public void setDate(Date date) {
super.setText(getDefaultDateFormat().format(date));
}
public Date getDate() {
try {
return getDefaultDateFormat().parse(getText());
} catch (ParseException e) {
return new Date();
}
}
private class DatePanel extends JPanel implements ChangeListener {
int startYear = 1980;
int lastYear = 2050;
Color backGroundColor = Color.gray;
Color palletTableColor = Color.white;
Color todayBackColor = Color.orange;
Color weekFontColor = Color.blue;
Color dateFontColor = Color.black;
Color weekendFontColor = Color.red;
Color controlLineColor = Color.pink;
Color controlTextColor = Color.white;
JSpinner yearSpin;
JSpinner monthSpin;
JButton[][] daysButton = new JButton[6][7];
DatePanel() {
setLayout(new BorderLayout());
setBorder(new LineBorder(backGroundColor, 2));
setBackground(backGroundColor);
JPanel topYearAndMonth = createYearAndMonthPanal();
add(topYearAndMonth, BorderLayout.NORTH);
JPanel centerWeekAndDay = createWeekAndDayPanal();
add(centerWeekAndDay, BorderLayout.CENTER);
reflushWeekAndDay();
}
private JPanel createYearAndMonthPanal() {
Calendar cal = getCalendar();
int currentYear = cal.get(Calendar.YEAR);
int currentMonth = cal.get(Calendar.MONTH) + 1;
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setBackground(controlLineColor);
yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
startYear, lastYear, 1));
yearSpin.setPreferredSize(new Dimension(56, 20));
yearSpin.setName("Year");
yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
yearSpin.addChangeListener(this);
panel.add(yearSpin);
JLabel yearLabel = new JLabel("Year");
yearLabel.setForeground(controlTextColor);
panel.add(yearLabel);
monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
12, 1));
monthSpin.setPreferredSize(new Dimension(35, 20));
monthSpin.setName("Month");
monthSpin.addChangeListener(this);
panel.add(monthSpin);
JLabel monthLabel = new JLabel("Month");
monthLabel.setForeground(controlTextColor);
panel.add(monthLabel);
return panel;
}
private JPanel createWeekAndDayPanal() {
String colname[] = { "S", "M", "T", "W", "T", "F", "S" };
JPanel panel = new JPanel();
panel.setFont(new Font("Arial", Font.PLAIN, 10));
panel.setLayout(new GridLayout(7, 7));
panel.setBackground(Color.white);
for (int i = 0; i < 7; i++) {
JLabel cell = new JLabel(colname[i]);
cell.setHorizontalAlignment(JLabel.RIGHT);
if (i == 0 || i == 6) {
cell.setForeground(weekendFontColor);
} else {
cell.setForeground(weekFontColor);
}
panel.add(cell);
}
int actionCommandId = 0;
for (int i = 0; i < 6; i++)
for (int j = 0; j < 7; j++) {
JButton numBtn = new JButton();
numBtn.setBorder(null);
numBtn.setHorizontalAlignment(SwingConstants.RIGHT);
numBtn.setActionCommand(String
.valueOf(actionCommandId));
numBtn.setBackground(palletTableColor);
numBtn.setForeground(dateFontColor);
numBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JButton source = (JButton) event.getSource();
if (source.getText().length() == 0) {
return;
}
dayColorUpdate(true);
source.setForeground(todayBackColor);
int newDay = Integer.parseInt(source.getText());
Calendar cal = getCalendar();
cal.set(Calendar.DAY_OF_MONTH, newDay);
setDate(cal.getTime());
dateDialog.setVisible(false);
}
});
if (j == 0 || j == 6)
numBtn.setForeground(weekendFontColor);
else
numBtn.setForeground(dateFontColor);
daysButton[i][j] = numBtn;
panel.add(numBtn);
actionCommandId++;
}
return panel;
}
private Calendar getCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(getDate());
return calendar;
}
private int getSelectedYear() {
return ((Integer) yearSpin.getValue()).intValue();
}
private int getSelectedMonth() {
return ((Integer) monthSpin.getValue()).intValue();
}
private void dayColorUpdate(boolean isOldDay) {
Calendar cal = getCalendar();
int day = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, 1);
int actionCommandId = day - 2 + cal.get(Calendar.DAY_OF_WEEK);
int i = actionCommandId / 7;
int j = actionCommandId % 7;
if (isOldDay) {
daysButton[i][j].setForeground(dateFontColor);
} else {
daysButton[i][j].setForeground(todayBackColor);
}
}
private void reflushWeekAndDay() {
Calendar cal = getCalendar();
cal.set(Calendar.DAY_OF_MONTH, 1);
int maxDayNo = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int dayNo = 2 - cal.get(Calendar.DAY_OF_WEEK);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
String s = "";
if (dayNo >= 1 && dayNo <= maxDayNo) {
s = String.valueOf(dayNo);
}
daysButton[i][j].setText(s);
dayNo++;
}
}
dayColorUpdate(false);
}
public void stateChanged(ChangeEvent e) {
dayColorUpdate(true);
JSpinner source = (JSpinner) e.getSource();
Calendar cal = getCalendar();
if (source.getName().equals("Year")) {
cal.set(Calendar.YEAR, getSelectedYear());
} else {
cal.set(Calendar.MONTH, getSelectedMonth() - 1);
}
setDate(cal.getTime());
reflushWeekAndDay();
}
}
}
You just have to go to the AndroidManifest.xml
and inside or in your activities labels, you have to type this line of code as someone up there said:
android:configChanges="orientation|screenSize"
So, you'll have something like this:
<activity android:name="ActivityMenu"
android:configChanges="orientation|screenSize">
</activity>
Hope it works!
You cannot move the mousepointer with javascript.
Just think about the implications for a second, if you could ;)
A couple of methods that, if the char does not exists, return the original string.
This one cuts the string after the first occurrence of the pivot:
public static string truncateStringAfterChar(string input, char pivot){
int index = input.IndexOf(pivot);
if(index >= 0) {
return input.Substring(index + 1);
}
return input;
}
This one instead cuts the string after the last occurrence of the pivot:
public static string truncateStringAfterLastChar(string input, char pivot){
return input.Split(pivot).Last();
}
One important advantage of BFS would be that it can be used to find the shortest path between any two nodes in an unweighted graph. Whereas, we cannot use DFS for the same.
the solution: for type entity use option "data" but value is a object. ie:
$em = $this->getDoctrine()->getEntityManager();
->add('sucursal', 'entity', array
(
'class' => 'TestGeneralBundle:Sucursal',
'property'=>'descripcion',
'label' => 'Sucursal',
'required' => false,
'data'=>$em->getReference("TestGeneralBundle:Sucursal",3)
))
I just add both these in my app.module.ts:
"import { HttpClientModule } from '@angular/common/http';
&
import { HttpModule } from '@angular/http';"
Now its works fine.... And dont forget to add in the
@NgModule => Imports:[] array
One more reason for the error.
if you are exporting after wrapping component with connect()() then props may give typescript error
Solution: I didn't explore much as I had the option of replacing connect function with useSelector hook
for example
/* Comp.tsx */
interface IComp {
a: number
}
const Comp = ({a}:IComp) => <div>{a}</div>
/* **
below line is culprit, you are exporting default the return
value of Connect and there is no types added to that return
value of that connect()(Comp)
** */
export default connect()(Comp)
--
/* App.tsx */
const App = () => {
/** below line gives same error
[ts] Argument of type 'number' is not assignable to
parameter of type 'never' */
return <Comp a={3} />
}
For enums, I test them only when they actually have methods in them. If it's a pure value-only enum like your example, I'd say don't bother.
But since you're keen on testing it, going with your second option is much better than the first. The problem with the first is that if you use an IDE, any renaming on the enums would also rename the ones in your test class.
Here is a rough but more declarative solution. I haven't been able to get it down to a single annotation, but this seems to work well. Also not sure about performance on large data sets.
Given this JSON:
{
"list": [
{
"wrapper": {
"name": "Jack"
}
},
{
"wrapper": {
"name": "Jane"
}
}
]
}
And these model objects:
public class RootObject {
@JsonProperty("list")
@JsonDeserialize(contentUsing = SkipWrapperObjectDeserializer.class)
@SkipWrapperObject("wrapper")
public InnerObject[] innerObjects;
}
and
public class InnerObject {
@JsonProperty("name")
public String name;
}
Where the Jackson voodoo is implemented like:
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface SkipWrapperObject {
String value();
}
and
public class SkipWrapperObjectDeserializer extends JsonDeserializer<Object> implements
ContextualDeserializer {
private Class<?> wrappedType;
private String wrapperKey;
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException {
SkipWrapperObject skipWrapperObject = property
.getAnnotation(SkipWrapperObject.class);
wrapperKey = skipWrapperObject.value();
JavaType collectionType = property.getType();
JavaType collectedType = collectionType.containedType(0);
wrappedType = collectedType.getRawClass();
return this;
}
@Override
public Object deserialize(JsonParser parser, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.readTree(parser);
JsonNode wrapped = objectNode.get(wrapperKey);
Object mapped = mapIntoObject(wrapped);
return mapped;
}
private Object mapIntoObject(JsonNode node) throws IOException,
JsonProcessingException {
JsonParser parser = node.traverse();
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(parser, wrappedType);
}
}
Hope this is useful to someone!
Hooks are a new feature in React v16.7.0-alpha
useState
is the “Hook”. useState()
set the default value of the any variable and manage in function component(PureComponent functions). ex : const [count, setCount] = useState(0);
set the default value of count 0. and u can use setCount
to increment
or decrement
the value. onClick={() => setCount(count + 1)}
increment the count value.DOC
I was already using jquery. But I think its intuitive enough to just have:
var total_amount = 0;
$.each(traveler, function( i, v ) { total_amount += v.Amount ; });
This is basically just a short-hand version of @akhouri's answer.
Your first problem is that you are passing -3 to the 2nd parameter of Columns.Add. It needs to be -2 for it to auto-size the column. Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columns.aspx (look at the comments on the code example at the bottom)
private void initListView()
{
// Add columns
lvRegAnimals.Columns.Add("Id", -2,HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);
}
You can also use the other overload, Add(string). E.g:
lvRegAnimals.Columns.Add("Id");
lvRegAnimals.Columns.Add("Name");
lvRegAnimals.Columns.Add("Age");
Reference for more overloads: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columnheadercollection.aspx
Second, to add items to the ListView, you need to create instances of ListViewItem and add them to the listView's Items collection. You will need to use the string[] constructor.
var item1 = new ListViewItem(new[] {"id123", "Tom", "24"});
var item2 = new ListViewItem(new[] {person.Id, person.Name, person.Age});
lvRegAnimals.Items.Add(item1);
lvRegAnimals.Items.Add(item2);
You can also store objects in the item's Tag property.
item2.Tag = person;
And then you can extract it
var person = item2.Tag as Person;
Let me know if you have any questions and I hope this helps!
var x = " Test Test Test ".split(" ").join(""); alert(x);
For step-by-step instructions, see this new MVC / EF tutorial series: http://www.asp.net/entity-framework/tutorials/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application The tutorial assumes you have installed the latest MVC 3 Tools Update and provides a link in case you haven't.
Different languages do different things with different levels of efficiency.
The Benchmarks Game has a whole load of different programming problems implemented in a lot of different languages.
These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit
for Chrome, Safari; -moz
for Firefox, -o
for Opera, -ms
for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.
This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.
To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:
.elementClass {
-moz-border-radius: 2em;
-ms-border-radius: 2em;
-o-border-radius: 2em;
-webkit-border-radius: 2em;
border-radius: 2em;
}
Specifically, to address the CSS in your question, the lines you quote:
-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;
Specify the column-count
, column-gap
and column-fill
properties for Webkit browsers and Firefox.
References:
var link = $("#me").closest(":has(h3 span b)").find('h3 span b');
Example: http://jsfiddle.net/e27r8/
This uses the closest()
[docs] method to get the first ancestor that has a nested h3 span b
, then does a .find()
.
Of course you could have multiple matches.
Otherwise, you're looking at doing a more direct traversal.
var link = $("#me").closest("h3 + div").prev().find('span b');
edit: This one works with your updated HTML.
Example: http://jsfiddle.net/e27r8/2/
EDIT: Updated to deal with updated question.
var link = $("#me").closest("h3 + *").prev().find('span b');
This makes the targeted element for .closest()
generic, so that even if there is no parent, it will still work.
Example: http://jsfiddle.net/e27r8/4/
I experienced this issue when calling my web api endpoint and solved it.
In my case it was an issue in the way the client was encoding the body content. I was not specifying the encoding or media type. Specifying them solved it.
Not specifying encoding type, caused 415 error:
var content = new StringContent(postData);
httpClient.PostAsync(uri, content);
Specifying the encoding and media type, success:
var content = new StringContent(postData, Encoding.UTF8, "application/json");
httpClient.PostAsync(uri, content);
It is true that, for 64-bit IEEE754 double, all integers up to 9007199254740992 == 2^53 can be exactly represented.
However, it is also worth mentioning that all representable numbers beyond 4503599627370496 == 2^52 are integers. Beyond 2^52 it becomes meaningless to test whether or not they are integers, because they are all implicitly rounded to a nearby representable value.
In the range 2^51 to 2^52, the only non-integer values are the midpoints ending with ".5", meaning any integer test after a calculation must be expected to yield at least 50% false answers.
Below 2^51 we also have ".25" and ".75", so comparing a number with its rounded counterpart in order to determine if it may be integer or not starts making some sense.
TLDR: If you want to test whether a calculated result may be integer, avoid numbers larger than 2251799813685248 == 2^51
If you use kotlin, it's really simple.
In your RecyclerAdapter class
userV.invalidateRecycler()
holder.card_User.setCardBackgroundColor(Color.parseColor("#3eb1ae").withAlpha(60))
In your fragment or Activity
override fun invalidateRecycler() {
if (v1.recyclerCompanies.childCount > 0) {
v1.recyclerCompanies.childrenRecursiveSequence().iterator().forEach { card ->
if (card is CardView) {
card.setCardBackgroundColor(Color.WHITE)
}
}
}
}
To see which ports are available on your machine run:
C:> netstat -an |find /i "listening"
Besides the box-shadow, transform and border options mentioned in other answers, WebKit browsers currently also obey -webkit-text-fill-color to set the colour of the "time elapsed" numbers, but since there is no way to set their background (which might vary with platform, e.g. inverted high-contrast modes on some operating systems), you would be advised to set -webkit-text-fill-color to the value "initial" if you've used it elsewhere and the audio element is inheriting this, otherwise some users might find those numbers unreadable.
One more time, building off of @RalphyZ
This one doesn't break the exposed API.
from argparse import ArgumentParser, SUPPRESS
# Disable default help
parser = ArgumentParser(add_help=False)
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
# Add back help
optional.add_argument(
'-h',
'--help',
action='help',
default=SUPPRESS,
help='show this help message and exit'
)
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
Which will show the same as above and should survive future versions:
usage: main.py [-h] [--required_arg REQUIRED_ARG]
[--optional_arg OPTIONAL_ARG]
required arguments:
--required_arg REQUIRED_ARG
optional arguments:
-h, --help show this help message and exit
--optional_arg OPTIONAL_ARG
Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship.
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
-qscale:v
to control qualityUse -qscale:v
(or the alias -q:v
) as an output option.
-qmin 1
output option (because the default is -qmin 2
).ffmpeg -i input.mp4 -qscale:v 2 output_%03d.jpg
See the image muxer documentation for more options involving image outputs.
ffmpeg -ss 60 -i input.mp4 -qscale:v 4 -frames:v 1 output.jpg
You could use MemoryMarshal API to perform very fast and efficient conversion. String
will implicitly be cast to ReadOnlySpan<byte>
, as MemoryMarshal.Cast
accepts either Span<byte>
or ReadOnlySpan<byte>
as an input parameter.
public static class StringExtensions
{
public static byte[] ToByteArray(this string s) => s.ToByteSpan().ToArray(); // heap allocation, use only when you cannot operate on spans
public static ReadOnlySpan<byte> ToByteSpan(this string s) => MemoryMarshal.Cast<char, byte>(s);
}
Following benchmark shows the difference:
Input: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,"
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated |
|----------------------------- |-----------:|----------:|----------:|-------:|------:|------:|----------:|
| UsingEncodingUnicodeGetBytes | 160.042 ns | 3.2864 ns | 6.4099 ns | 0.0780 | - | - | 328 B |
| UsingMemoryMarshalAndToArray | 31.977 ns | 0.7177 ns | 1.5753 ns | 0.0781 | - | - | 328 B |
| UsingMemoryMarshal | 1.027 ns | 0.0565 ns | 0.1630 ns | - | - | - | - |
Each control deriving from Panel
implements distinct layout logic performed in Measure()
and Arrange()
:
Measure()
determines the size of the panel and each of its childrenArrange()
determines the rectangle where each control rendersThe last child of the DockPanel
fills the remaining space. You can disable this behavior by setting the LastChild
property to false
.
The StackPanel
asks each child for its desired size and then stacks them. The stack panel calls Measure()
on each child, with an available size of Infinity
and then uses the child's desired size.
A Grid
occupies all available space, however, it will set each child to their desired size and then center them in the cell.
You can implement your own layout logic by deriving from Panel
and then overriding MeasureOverride()
and ArrangeOverride()
.
See this article for a simple example.
I just wrote a version of this called "get_caller", I hope it helps. Mine is pretty lazy. You can just run get_caller() from a function, you don't have to specify it like this:
get_caller(__FUNCTION__);
Here's the script in full with a quirky test case:
<?php
/* This function will return the name string of the function that called $function. To return the
caller of your function, either call get_caller(), or get_caller(__FUNCTION__).
*/
function get_caller($function = NULL, $use_stack = NULL) {
if ( is_array($use_stack) ) {
// If a function stack has been provided, used that.
$stack = $use_stack;
} else {
// Otherwise create a fresh one.
$stack = debug_backtrace();
echo "\nPrintout of Function Stack: \n\n";
print_r($stack);
echo "\n";
}
if ($function == NULL) {
// We need $function to be a function name to retrieve its caller. If it is omitted, then
// we need to first find what function called get_caller(), and substitute that as the
// default $function. Remember that invoking get_caller() recursively will add another
// instance of it to the function stack, so tell get_caller() to use the current stack.
$function = get_caller(__FUNCTION__, $stack);
}
if ( is_string($function) && $function != "" ) {
// If we are given a function name as a string, go through the function stack and find
// it's caller.
for ($i = 0; $i < count($stack); $i++) {
$curr_function = $stack[$i];
// Make sure that a caller exists, a function being called within the main script
// won't have a caller.
if ( $curr_function["function"] == $function && ($i + 1) < count($stack) ) {
return $stack[$i + 1]["function"];
}
}
}
// At this stage, no caller has been found, bummer.
return "";
}
// TEST CASE
function woman() {
$caller = get_caller(); // No need for get_caller(__FUNCTION__) here
if ($caller != "") {
echo $caller , "() called " , __FUNCTION__ , "(). No surprises there.\n";
} else {
echo "no-one called ", __FUNCTION__, "()\n";
}
}
function man() {
// Call the woman.
woman();
}
// Don't keep him waiting
man();
// Try this to see what happens when there is no caller (function called from main script)
//woman();
?>
man() calls woman(), who calls get_caller(). get_caller() doesn't know who called it yet, because the woman() was cautious and didn't tell it, so it recurses to find out. Then it returns who called woman(). And the printout in source-code mode in a browser shows the function stack:
Printout of Function Stack:
Array
(
[0] => Array
(
[file] => /Users/Aram/Development/Web/php/examples/get_caller.php
[line] => 46
[function] => get_caller
[args] => Array
(
)
)
[1] => Array
(
[file] => /Users/Aram/Development/Web/php/examples/get_caller.php
[line] => 56
[function] => woman
[args] => Array
(
)
)
[2] => Array
(
[file] => /Users/Aram/Development/Web/php/examples/get_caller.php
[line] => 60
[function] => man
[args] => Array
(
)
)
)
man() called woman(). No surprises there.
There are 2 solutions for your problem:
mw.geometry('500x500')
OR
back.place(x = 0, y = 0, relwidth = 1, relheight = 1)
*The second option should be used in place of back.pack()
String methods return the modified string.
k = [x.replace(' ', '') for x in hello]
First, add a textView in the XML file
<TextView
android:id="@+id/rate_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/what_U_want_to_display_in_first_time"
/>
then add a button in xml file with id btn_change_textView and write this two line of code in onCreate()
method of activity
Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);
then use clickListener()
on button object like this
btn.setOnClickListener(new View.OnClickListener {
public void onClick(View v) {
textView.setText("write here what u want to display after button click in string");
}
});
public class StringToLong {
public static void main (String[] args) {
// String s = "fred"; // do this if you want an exception
String s = "100";
try {
long l = Long.parseLong(s);
System.out.println("long l = " + l);
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
If your click handler is successfully called then this should work:
$('#results').on('click', '.item', function () {
var NestId = $(this).data('id');
var url = "/Artists/Details?NestId=" + NestId;
window.location.href = url;
})
EDIT: In this particular case given that the action method parameter is a string which is nullable, then if NestId == null
, won't cause any exception at all, given that the ModelBinder won't complain about it.
I made a simpler way to set a min/max to an Edittext. I use arithmetic keypad and I work with this method:
private int limit(EditText x,int z,int limin,int limax){
if( x.getText().toString()==null || x.getText().toString().length()==0){
x.setText(Integer.toString(limin));
return z=0;
}
else{
z = Integer.parseInt(x.getText().toString());
if(z <limin || z>limax){
if(z<10){
x.setText(Integer.toString(limin));
return z=0;
}
else{
x.setText(Integer.toString(limax));
return z=limax;
}
}
else
return z = Integer.parseInt(x.getText().toString());
}
}
The method accepts all of your values but if a value of users in not adhere to your limits it will be set automatically to the min/max limit. For ex. limit limin=10, limax =80 if the user sets 8, automatically 10 is saved to a variable and EditText is set to 10.
Use this XPath expression:
/*/*/X/node()
This selects any node (element, text node, comment or processing instruction) that is a child of any X
element that is a grand-child of the top element of the XML document.
To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:copy-of select="/*/*/X/node()"/>
</xsl:template>
</xsl:stylesheet>
and it produces exactly the wanted, correct result:
First Text Node #1
<y> Y can Have Child Nodes #
<child> deep to it </child>
</y> Second Text Node #2
<z />
Explanation:
As defined in the W3 XPath 1.0 Spec, "child::node()
selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.
node()
is an abbreviation of child::node()
(because child::
is the primary axis and is used when no axis is explicitly specified).
A few examples follow, going from basic through to adding transformations after the request and/or error handling:
// Implementation code where T is the returned data shape
function api<T>(url: string): Promise<T> {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json<T>()
})
}
// Consumer
api<{ title: string; message: string }>('v1/posts/1')
.then(({ title, message }) => {
console.log(title, message)
})
.catch(error => {
/* show error message */
})
Often you may need to do some tweaks to the data before its passed to the consumer, for example, unwrapping a top level data attribute. This is straight forward:
function api<T>(url: string): Promise<T> {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json<{ data: T }>()
})
.then(data => { /* <-- data inferred as { data: T }*/
return data.data
})
}
// Consumer - consumer remains the same
api<{ title: string; message: string }>('v1/posts/1')
.then(({ title, message }) => {
console.log(title, message)
})
.catch(error => {
/* show error message */
})
I'd argue that you shouldn't be directly error catching directly within this service, instead, just allowing it to bubble, but if you need to, you can do the following:
function api<T>(url: string): Promise<T> {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json<{ data: T }>()
})
.then(data => {
return data.data
})
.catch((error: Error) => {
externalErrorLogging.error(error) /* <-- made up logging service */
throw error /* <-- rethrow the error so consumer can still catch it */
})
}
// Consumer - consumer remains the same
api<{ title: string; message: string }>('v1/posts/1')
.then(({ title, message }) => {
console.log(title, message)
})
.catch(error => {
/* show error message */
})
There has been some changes since writing this answer a while ago. As mentioned in the comments, response.json<T>
is no longer valid. Not sure, couldn't find where it was removed.
For later releases, you can do:
// Standard variation
function api<T>(url: string): Promise<T> {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json() as Promise<T>
})
}
// For the "unwrapping" variation
function api<T>(url: string): Promise<T> {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json() as Promise<{ data: T }>
})
.then(data => {
return data.data
})
}
Adding the following lines at the bottom of your batch file will grab everything just as displayed inside the CMD window and export into a text file:
powershell -c "$wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys('^a')
powershell -c "$wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys('^c')
powershell Get-Clipboard > MyLog.txt
It basically performs a select all -> copy into clipboard -> paste into text file.
After you extract your "selenium-java-.zip" file you need to configure your build path from your IDE. Import all the jar files under "lib" folder and both selenium standalone server & Selenium java version jar files.
The following works for me:
compile fileTree(dir: 'libs', include: '*.jar')
Refer to the Gradle Documentation.
EADDRINUSE
means that the port(which we try to listen in node application) is already being used. In order to overcome, we need to identify which process is running with that port.
For example if we are trying to listen our node application in 3000 port. We need to check whether that port is already is being used by any other process.
$sudo netstat -plunt |grep :3000
That the above command gives below result.
tcp6 0 0 :::3000 :::* LISTEN 25315/node
Now you got process ID(25315), Kill that process.
kill -9 25315
npm run start
Note: This solution for linux users.
Omit the parenthesis:
ALTER TABLE User
ADD CONSTRAINT userProperties
FOREIGN KEY(properties)
REFERENCES Properties(ID)
I can confirm that I have the same bug on Windows 7 using Chrome Version 35 but I share my partial solution who is open a new tab on Chrome and showing a dialog.
For other browser when the user click on cancel automatically close the new print window.
//Chrome's versions > 34 is some bug who stop all javascript when is show a prints preview
//http://stackoverflow.com/questions/23071291/javascript-window-print-in-chrome-closing-new-window-or-tab-instead-of-cancel
if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
var popupWin = window.open();
popupWin.window.focus();
popupWin.document.write('<!DOCTYPE html><html><head>' +
'<link rel="stylesheet" type="text/css" href="style.css" />' +
'</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div></html>');
popupWin.onbeforeunload = function (event) {
return 'Please use the cancel button on the left side of the print preview to close this window.\n';
};
}else {
var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
popupWin.document.write('<!DOCTYPE html><html><head>' +
'<link rel="stylesheet" type="text/css" href="style.css" />' +
'</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div>' +
'<script>setTimeout(function(){ window.parent.focus(); window.close() }, 100)</script></html>');
}
popupWin.document.close();
Although hashcode does nothing with your business logic, we have to take care of it in most cases. Because when your object is put into a hash based container(HashSet
, HashMap
...), the container puts/gets the element's hashcode.
On the Unity Editor open your project and:
If you already created your empty git repo on-line (eg. github.com) now it's time to upload your code. Open a command prompt and follow the next steps:
cd to/your/unity/project/folder
git init
git add *
git commit -m "First commit"
git remote add origin [email protected]:username/project.git
git push -u origin master
You should now open your Unity project while holding down the Option or the Left Alt key. This will force Unity to recreate the Library directory (this step might not be necessary since I've seen Unity recreating the Library directory even if you don't hold down any key).
Finally have git ignore the Library and Temp directories so that they won’t be pushed to the server. Add them to the .gitignore file and push the ignore to the server. Remember that you'll only commit the Assets and ProjectSettings directories.
And here's my own .gitignore recipe for my Unity projects:
# =============== #
# Unity generated #
# =============== #
Temp/
Obj/
UnityGenerated/
Library/
Assets/AssetStoreTools*
# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
*.svd
*.userprefs
*.csproj
*.pidb
*.suo
*.sln
*.user
*.unityproj
*.booproj
# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db
As someone who has been interested in this for a VERY LONG TIME. See from the manual:
$XDG_CONFIG_HOME/git/config - Second user-specific configuration file. If $XDG_CONFIG_HOME
is not set or empty, $HOME/.config/git/config will be used. Any single-valued variable set in this file will be overwritten by whatever is in ~/.gitconfig. It is a good idea not to create this file if you sometimes use older versions of Git, as support for this file was added fairly recently.
Which was only recently added. This dump is from 2.15.0.
Works for me.
Share application with title is you app_name, content is your application link
private static void shareApp(Context context) {
final String appPackageName = BuildConfig.APPLICATION_ID;
final String appName = context.getString(R.string.app_name);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String shareBodyText = "https://play.google.com/store/apps/details?id=" +
appPackageName;
shareIntent.putExtra(Intent.EXTRA_SUBJECT, appName);
shareIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
context.startActivity(Intent.createChooser(shareIntent, context.getString(R.string
.share_with)));
}
the better approach for sending data from activity class to fragment is passing via setter methods. Like
FragmentClass fragmentClass = new FragmentClass();
fragmentClass.setMyList(mylist);
fragmentClass.setMyString(myString);
fragmentClass.setMyMap(myMap);
and get these data from the class easily.
You can use Collections
for to sort data:
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
public class tes
{
public static void main(String args[])
{
List<Integer> lList = new ArrayList<Integer>();
lList.add(4);
lList.add(1);
lList.add(7);
lList.add(2);
lList.add(9);
lList.add(1);
lList.add(5);
Collections.sort(lList);
for(int i=0; i<lList.size();i++ )
{
System.out.println(lList.get(i));
}
}
}
You can easily do this in Kotlin using the following code:
val fileData = "your_json_string"
val gson = GsonBuilder().create()
val packagesArray = gson.fromJson(fileData , Array<YourClass>::class.java).toList()
Basically, you only need to provide an Array
of YourClass
objects.
typedef enum state {DEAD,ALIVE} State;
| | | | | |^ terminating semicolon, required!
| | | type specifier | | |
| | | | ^^^^^ declarator (simple name)
| | | |
| | ^^^^^^^^^^^^^^^^^^^^^^^
| |
^^^^^^^-- storage class specifier (in this case typedef)
The typedef
keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern
or static
is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.
After the above declaration, the State
identifier becomes an alias for the type enum state {DEAD,ALIVE}
. The declaration also provides that type itself. However that isn't typedef
doing it. Any declaration in which enum state {DEAD,ALIVE}
appears as a type specifier introduces that type into the scope:
enum state {DEAD, ALIVE} stateVariable;
If enum state
has previously been introduced the typedef
has to be written like this:
typedef enum state State;
otherwise the enum
is being redefined, which is an error.
Like other declarations (except function parameter declarations), the typedef
declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:
typedef unsigned long ulong, *ulongptr;
| | | | | 1 | | 2 |
| | | | | | ^^^^^^^^^--- "pointer to" declarator
| | | | ^^^^^^------------- simple declarator
| | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier
This typedef
introduces two type names ulong
and ulongptr
, based on the unsigned long
type given in the specifier-qualifier list. ulong
is just a straight alias for that type. ulongptr
is declared as a pointer to unsigned long
, thanks to the *
syntax, which in this role is a kind of type construction operator which deliberately mimics the unary *
for pointer dereferencing used in expressions. In other words ulongptr
is an alias for the "pointer to unsigned long
" type.
Alias means that ulongptr
is not a distinct type from unsigned long *
. This is valid code, requiring no diagnostic:
unsigned long *p = 0;
ulongptr q = p;
The variables q
and p
have exactly the same type.
The aliasing of typedef
isn't textual. For instance if user_id_t
is a typedef
name for the type int
, we may not simply do this:
unsigned user_id_t uid; // error! programmer hoped for "unsigned int uid".
This is an invalid type specifier list, combining unsigned
with a typedef name. The above can be done using the C preprocessor:
#define user_id_t int
unsigned user_id_t uid;
whereby user_id_t
is macro-expanded to the token int
prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.
Among the disadvantages that it doesn't work well for derived types:
#define silly_macro int *
silly_macro not, what, you, think;
This declaration doesn't declare what
, you
and think
as being of type "pointer to int" because the macro-expansion is:
int * not, what, you, think;
The type specifier is int
, and the declarators are *not
, what
, you
and think
. So not
has the expected pointer type, but the remaining identifiers do not.
And that's probably 99% of everything about typedef
and type aliasing in C.
After applying the top rated solution I've had a problem that it breaks future modals opening properly. I've found my solution which works good
element.on("shown.bs.modal", function () {
if ($(".modal-backdrop").length > 1) {
$(".modal-backdrop").not(':first').remove();
}
element.css('display', 'block');
});
Make sure your computer is connected to the internet, then click on the link that comes with the error message i.e "install missing platform(s) and sync project". Give it a few seconds especially if your computer has low specs, it will bring up a window called SDK Quickfix Installation and everything is straightforward from there.
Hu! Damn I was struggling whole day for this. Somehow I got workaround though I would't recommend it. You will have to use Handler to achieve this.
call getDialogBack
function to get
boolean result = getDialogBack(this);
Log.d(TAG, "onCreate: "+result);
In getDialogBack
write dialog and handler code to make it synchronous
public int getDialogBack(Context context,int i) {
final Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message mesg) {
throw new RuntimeException();
}
};
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Title");
alert.setMessage("Message");
alert.setPositiveButton("Want to print next", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
handler.sendMessage(handler.obtainMessage());
}
});
alert.setNegativeButton("Return False", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
handler.sendMessage(handler.obtainMessage());
}
});
alert.show();
try {
Looper.loop();
} catch (RuntimeException e) {
}
return true;
}
Just Try This :
textfield.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
if(textfield.getText().length()>=5&&!(evt.getKeyChar()==KeyEvent.VK_DELETE||evt.getKeyChar()==KeyEvent.VK_BACK_SPACE)) {
getToolkit().beep();
evt.consume();
}
}
});
For those who have a file from an input control, don't know what its orientation is, are a bit lazy and don't want to include a large library below is the code provided by @WunderBart melded with the answer he links to (https://stackoverflow.com/a/32490603) that finds the orientation.
function getDataUrl(file, callback2) {
var callback = function (srcOrientation) {
var reader2 = new FileReader();
reader2.onload = function (e) {
var srcBase64 = e.target.result;
var img = new Image();
img.onload = function () {
var width = img.width,
height = img.height,
canvas = document.createElement('canvas'),
ctx = canvas.getContext("2d");
// set proper canvas dimensions before transform & export
if (4 < srcOrientation && srcOrientation < 9) {
canvas.width = height;
canvas.height = width;
} else {
canvas.width = width;
canvas.height = height;
}
// transform context before drawing image
switch (srcOrientation) {
case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
case 3: ctx.transform(-1, 0, 0, -1, width, height); break;
case 4: ctx.transform(1, 0, 0, -1, 0, height); break;
case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
case 6: ctx.transform(0, 1, -1, 0, height, 0); break;
case 7: ctx.transform(0, -1, -1, 0, height, width); break;
case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
default: break;
}
// draw image
ctx.drawImage(img, 0, 0);
// export base64
callback2(canvas.toDataURL());
};
img.src = srcBase64;
}
reader2.readAsDataURL(file);
}
var reader = new FileReader();
reader.onload = function (e) {
var view = new DataView(e.target.result);
if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
var length = view.byteLength, offset = 2;
while (offset < length) {
var marker = view.getUint16(offset, false);
offset += 2;
if (marker == 0xFFE1) {
if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);
var little = view.getUint16(offset += 6, false) == 0x4949;
offset += view.getUint32(offset + 4, little);
var tags = view.getUint16(offset, little);
offset += 2;
for (var i = 0; i < tags; i++)
if (view.getUint16(offset + (i * 12), little) == 0x0112)
return callback(view.getUint16(offset + (i * 12) + 8, little));
}
else if ((marker & 0xFF00) != 0xFF00) break;
else offset += view.getUint16(offset, false);
}
return callback(-1);
};
reader.readAsArrayBuffer(file);
}
which can easily be called like such
getDataUrl(input.files[0], function (imgBase64) {
vm.user.BioPhoto = imgBase64;
});
Escape the variable in order to access variables outside of the ssh session: ssh [email protected] "~/tools/myScript.pl \$BUILD_NUMBER"
The big difference is perfectly explained here.
Basically, lightweight tags are just pointers to specific commits. No further information is saved; on the other hand, annotated tags are regular objects, which have an author and a date and can be referred because they have their own SHA key.
If knowing who tagged what and when is relevant for you, then use annotated tags. If you just want to tag a specific point in your development, no matter who and when did that, then lightweight tags are good enough.
Normally you'd go for annotated tags, but it is really up to the Git master of the project.
I have solved similar problems by writing a Generic Extension Property Attribute Helper:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
public static class AttributeHelper
{
public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(
Expression<Func<T, TOut>> propertyExpression,
Func<TAttribute, TValue> valueSelector)
where TAttribute : Attribute
{
var expression = (MemberExpression) propertyExpression.Body;
var propertyInfo = (PropertyInfo) expression.Member;
var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
return attr != null ? valueSelector(attr) : default(TValue);
}
}
Usage:
var author = AttributeHelper.GetPropertyAttributeValue<Book, string, AuthorAttribute, string>(prop => prop.Name, attr => attr.Author);
// author = "AuthorName"
here's how you can do it with a cool shell trick:
mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'
'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.
use the -t flag to enable table-format output
You can (A) change the markup to not use paragraphs
<span>Text</span>
<br>
<ul>
<li>One</li>
</ul>
<span>Text 2</span>
Or (B) change the css
p{margin:0px;}
Demos here: http://jsfiddle.net/ZnpVu/1
Assuming you want to do it yourself and not rely upon other providers, IP2Nation provides a MySQL database of the mappings which are updated as the regional registries change things around.
A view is a virtual table, which provides access to a subset of column from one or more table. A view can derive its data from one or more table. An output of query can be stored as a view. View act like small a table but it does not physically take any space. View is good way to present data in particular users from accessing the table directly. A view in oracle is nothing but a stored sql scripts. Views itself contain no data.
Creating it once and using it wherever needed is a good idea. Add this in your styles.xml:
<style name="Divider">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">1dp</item>
<item name="android:background">?android:attr/listDivider</item>
</style>
and add this in your xml code, where a line divider is needed:
<View style="@style/Divider"/>
Originally answered by toddles_fp to this question: Android Drawing Separator/Divider Line in Layout?
The n
module worked for me.
Run this code to clear npm’s cache, install n, and install the latest stable version of Node:
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
See: http://www.hostingadvice.com/how-to/update-node-js-latest-version/
And: https://www.npmjs.com/package/n
To install a specific version of node:
sudo n 6.11.2
To check what version:
node -v
You might need to restart
<Label x:Name="datetimeofmsg"
HorizontalAlignment="Left" Margin="4.286,55,0,0"
VerticalAlignment="Top" Background="{x:Null}"
FontWeight="Bold" Width="61.714" Height="20" Foreground="White">
<Label.Content>
<AccessText TextWrapping="Wrap"/>
</Label.Content>
</Label>
If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:
Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);
Hope it helps.
Generally it means that you are providing an index for which a list element does not exist.
E.g, if your list was [1, 3, 5, 7]
, and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.
You need the *
so it says "zero or more of the previous character" and this should do it:
var reg = new RegExp('^\\d*$');
This answer is late, but hopefully it helps others.
I have had the same experience of not being able to connect. Rebooting phone and PC does not help. I found the fix at: http://developer.android.com/tools/help/adb.html at the bottom of the page.
Basically you follow these steps:
adb usb
adb tcpip 5555
adb connect xxx.xxx.xxx.xxx
Where xxx.xxx.xxx.xxx is your phone's IP address.
Of course it is right what you say at the beginning, and C logical operator &&
and ||
are what you usually use to "connect" conditions (expressions that can be evaluated as true or false); the comma operator is not a logical operator and its use in that example makes no sense, as explained by other users. You can use it e.g. to "concatenate" statements in the for itself: you can initialize and update j altogether with i; or use the comma operator in other ways
#include <stdio.h>
int main(void) // as std wants
{
int i, j;
// init both i and j; condition, we suppose && is the "original"
// intention; update i and j
for(i=0, j=2; j>=0 && i<=5; i++, j--)
{
printf("%d ", i+j);
}
return 0;
}
Java is a byte-compiled language targeting a platform called the Java Virtual Machine which is stack-based and has some very fast implementations on many platforms.
This is how to assign a value to a variable:
SELECT @EmpID = Id
FROM dbo.Employee
However, the above query is returning more than one value. You'll need to add a WHERE
clause in order to return a single Id
value.
This works as of android 7.1.1, non-rooted
adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings && adb shell input keyevent 23 && adb shell input keyevent 23
This will launch the activity and then send the DPAD center keyevent. I added another DPAD center as an experiment to see if you can enable it in the same way.
I've found the best way to program the font sizes of a website are to define a base font size for the body
and then use em's (or rem's) for every other font-size
I declare after that. That's personal preference I suppose, but it's served me well and also made it very easy to incorporate a more responsive design.
As far as using rem units go, I think it's good to find a balance between being progressive in your code, but to also offer support for older browsers. Check out this link about browser support for rem units, that should help out a good amount on your decision.
You need to use padding on your td
elements. Something like this should do the trick. You can, of course, get the same result using a top padding instead of a bottom padding.
In the CSS code below, the greater-than sign means that the padding is only applied to td
elements that are direct children to tr
elements with the class spaceUnder
. This will make it possible to use nested tables. (Cell C and D in the example code.) I'm not too sure about browser support for the direct child selector (think IE 6), but it shouldn't break the code in any modern browsers.
/* Apply padding to td elements that are direct children of the tr elements with class spaceUnder. */_x000D_
_x000D_
tr.spaceUnder>td {_x000D_
padding-bottom: 1em;_x000D_
}
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>A</td>_x000D_
<td>B</td>_x000D_
</tr>_x000D_
<tr class="spaceUnder">_x000D_
<td>C</td>_x000D_
<td>D</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>E</td>_x000D_
<td>F</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
This should render somewhat like this:
+---+---+
| A | B |
+---+---+
| C | D |
| | |
+---+---+
| E | F |
+---+---+
The reason behind posted this answer is I tried many solution but no one work properly, most of the answer not work in case where have to set cookie first time, and got result cookie not sync first time, Please use this solution it work for both iOS >= 11.0 <= iOS 11 till 8.0, also work with cookie sync first time.
For iOS >= 11.0 -- Swift 4.2
Get http cookies and set in wkwebview cookie store like this way, it's very tricky point to load your request in wkwebview, must sent request for loading when cookies gonna be set completely, here is function that i wrote.
Call function with closure in completion you call load webview. FYI this function only handle iOS >= 11.0
self.WwebView.syncCookies {
if let request = self.request {
self.WwebView.load(request)
}
}
Here is implementation for syncCookies function.
func syncCookies(completion:@escaping ()->Void) {
if #available(iOS 11.0, *) {
if let yourCookie = "HERE_YOUR_HTTP_COOKIE_OBJECT" {
self.configuration.websiteDataStore.httpCookieStore.setCookie(yourCookie, completionHandler: {
completion()
})
}
} else {
//Falback just sent
completion()
}
}
For iOS 8 till iOS 11
you need to setup some extra things you need to set two time cookies one through using WKUserScript and dont forget to add cookies in request as well, otherwise your cookie not sync first time and you will see you page not load first time properly. this is the heck that i found to support cookies for iOS 8.0
before you Wkwebview object creation.
func setUpWebView() {
let userController: WKUserContentController = WKUserContentController.init()
if IOSVersion.SYSTEM_VERSION_LESS_THAN(version: "11.0") {
if let cookies = HTTPCookieStorage.shared.cookies {
if let script = getJSCookiesString(for: cookies) {
cookieScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false)
userController.addUserScript(cookieScript!)
}
}
}
let webConfiguration = WKWebViewConfiguration()
webConfiguration.processPool = BaseWebViewController.processPool
webConfiguration.userContentController = userController
let customFrame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 0.0, height: self.webContainerView.frame.size.height))
self.WwebView = WKWebView (frame: customFrame, configuration: webConfiguration)
self.WwebView.translatesAutoresizingMaskIntoConstraints = false
self.webContainerView.addSubview(self.WwebView)
self.WwebView.uiDelegate = self
self.WwebView.navigationDelegate = self
self.WwebView.allowsBackForwardNavigationGestures = true // A Boolean value indicating whether horizontal swipe gestures will trigger back-forward list navigations
self.WwebView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
self.view.addConstraint(NSLayoutConstraint(item: WwebView, attribute: .trailing, relatedBy: .equal, toItem: self.webContainerView, attribute: .trailing, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: WwebView, attribute: .leading, relatedBy: .equal, toItem: self.webContainerView, attribute: .leading, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: WwebView, attribute: .top, relatedBy: .equal, toItem: self.webContainerView, attribute: .top, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: WwebView, attribute: .bottom, relatedBy: .equal, toItem: self.webContainerView, attribute: .bottom, multiplier: 1, constant: 0))
}
Focus on this function getJSCookiesString
public func getJSCookiesString(for cookies: [HTTPCookie]) -> String? {
var result = ""
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"
for cookie in cookies {
if cookie.name == "yout_cookie_name_want_to_sync" {
result += "document.cookie='\(cookie.name)=\(cookie.value); domain=\(cookie.domain); path=\(cookie.path); "
if let date = cookie.expiresDate {
result += "expires=\(dateFormatter.string(from: date)); "
}
if (cookie.isSecure) {
result += "secure; "
}
result += "'; "
}
}
return result
}
Here is other step wkuserscript not sync cookies immediately, there a lot of heck to load first time page with cookie one is to reload webview again if it terminate process but i don't recommend to use it, its not good for user point of view, heck is whenever you ready to load request set cookies in request header as well like this way, don't forget to add iOS version check. before load request call this function.
request?.addCookies()
i wrote extension for URLRequest
extension URLRequest {
internal mutating func addCookies() {
//"appCode=anAuY28ucmFrdXRlbi5yZXdhcmQuaW9zLXpOQlRTRmNiejNHSzR0S0xuMGFRb0NjbUg4Ql9JVWJH;rpga=kW69IPVSYZTo0JkZBicUnFxC1g5FtoHwdln59Z5RNXgJoMToSBW4xAMqtf0YDfto;rewardadid=D9F8CE68-CF18-4EE6-A076-CC951A4301F6;rewardheader=true"
var cookiesStr: String = ""
if IOSVersion.SYSTEM_VERSION_LESS_THAN(version: "11.0") {
let mutableRequest = ((self as NSURLRequest).mutableCopy() as? NSMutableURLRequest)!
if let yourCookie = "YOUR_HTTP_COOKIE_OBJECT" {
// if have more than one cookies dont forget to add ";" at end
cookiesStr += yourCookie.name + "=" + yourCookie.value + ";"
mutableRequest.setValue(cookiesStr, forHTTPHeaderField: "Cookie")
self = mutableRequest as URLRequest
}
}
}
}
now you ready to go for testing iOS > 8
Partial solution: for a single string column
tmp = df['A1'].fillna(''); isEmpty = tmp==''
gives boolean Series of True where there are empty strings or NaN values.
It took me a while to figure this out too. url_for
in Flask looks for endpoints that you specified in the routes.py
script.
So if you have a decorator in your routes.py
file like @blah.route('/folder.subfolder')
then Flask will recognize the command {{ url_for('folder.subfolder') , filename = "some_image.jpg" }}
. The 'folder.subfolder'
argument sends it to a Flask endpoint it recognizes.
However let us say that you stored your image file, some_image.jpg
, in your subfolder, BUT did not specify this subfolder as a route endpoint in your flask routes.py
, your route decorator looks like @blah.routes('/folder')
. You then have to ask for your image file this way:
{{ url_for('folder'), filename = 'subfolder/some_image.jpg' }}
I.E. you tell Flask to go to the endpoint it knows, "folder", then direct it from there by putting the subdirectory path in the filename argument.
Try this:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
p {
text-align: right;
}
input {
width: 100px;
}
</style>
</head>
<body>
<form>
<p>
<input name="declared_first" value="above" />
</p>
<p>
<input name="declared_second" value="below" />
</p>
</form>
</body>
</html>
The &&
and ||
operators "short-circuit", meaning they don't evaluate the right-hand side if it isn't necessary.
The &
and |
operators, when used as logical operators, always evaluate both sides.
There is only one case of short-circuiting for each operator, and they are:
false && ...
- it is not necessary to know what the right-hand side is because the result can only be false
regardless of the value theretrue || ...
- it is not necessary to know what the right-hand side is because the result can only be true
regardless of the value thereLet's compare the behaviour in a simple example:
public boolean longerThan(String input, int length) {
return input != null && input.length() > length;
}
public boolean longerThan(String input, int length) {
return input != null & input.length() > length;
}
The 2nd version uses the non-short-circuiting operator &
and will throw a NullPointerException
if input
is null
, but the 1st version will return false
without an exception.
This is pure JPA without using getters/setters. As of 2013/2014 it is the best answer without using any Hibernate specific annotations, but please note this solution is JPA 2.1, and was not available when the question was first asked:
@Entity
public class Person {
@Convert(converter=BooleanToStringConverter.class)
private Boolean isAlive;
...
}
And then:
@Converter
public class BooleanToStringConverter implements AttributeConverter<Boolean, String> {
@Override
public String convertToDatabaseColumn(Boolean value) {
return (value != null && value) ? "Y" : "N";
}
@Override
public Boolean convertToEntityAttribute(String value) {
return "Y".equals(value);
}
}
Edit:
The implementation above considers anything different from character "Y", including null
, as false
. Is that correct? Some people here consider this incorrect, and believe that null
in the database should be null
in Java.
But if you return null
in Java, it will give you a NullPointerException
if your field is a primitive boolean. In other words, unless some of your fields actually use the class Boolean it's best to consider null
as false
, and use the above implementation. Then Hibernate will not to emit any exceptions regardless of the contents of the database.
And if you do want to accept null
and emit exceptions if the contents of the database are not strictly correct, then I guess you should not accept any characters apart from "Y", "N" and null
. Make it consistent, and don't accept any variations like "y", "n", "0" and "1", which will only make your life harder later. This is a more strict implementation:
@Override
public String convertToDatabaseColumn(Boolean value) {
if (value == null) return null;
else return value ? "Y" : "N";
}
@Override
public Boolean convertToEntityAttribute(String value) {
if (value == null) return null;
else if (value.equals("Y")) return true;
else if (value.equals("N")) return false;
else throw new IllegalStateException("Invalid boolean character: " + value);
}
And yet another option, if you want to allow for null
in Java but not in the database:
@Override
public String convertToDatabaseColumn(Boolean value) {
if (value == null) return "-";
else return value ? "Y" : "N";
}
@Override
public Boolean convertToEntityAttribute(String value) {
if (value.equals("-") return null;
else if (value.equals("Y")) return true;
else if (value.equals("N")) return false;
else throw new IllegalStateException("Invalid boolean character: " + value);
}
IE needs a plugin to display SVG. Most common is the one available for download by Adobe; however, Adobe no longer supports or develops it. Firefox, Opera, Chrome, Safari, will all display basic SVG fine but will run into quirks if advanced features are used, as support is incomplete. Firefox has no support for declarative animation.
SVG elements can be created with javascript as follows:
// "circle" may be any tag name
var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
// Set any attributes as desired
shape.setAttribute("cx", 25);
shape.setAttribute("cy", 25);
shape.setAttribute("r", 20);
shape.setAttribute("fill", "green");
// Add to a parent node; document.documentElement should be the root svg element.
// Acquiring a parent element with document.getElementById() would be safest.
document.documentElement.appendChild(shape);
The SVG specification describes the DOM interfaces for all SVG elements. For example, the SVGCircleElement, which is created above, has cx
, cy
, and r
attributes for the center point and radius, which can be directly accessed. These are the SVGAnimatedLength attributes, which have a baseVal
property for the normal value, and an animVal
property for the animated value. Browsers at the moment are not reliably supporting the animVal
property. baseVal
is an SVGLength, whose value is set by the value
property.
Hence, for script animations, one can also set these DOM properties to control SVG. The following code should be equivalent to the above code:
var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
shape.cx.baseVal.value = 25;
shape.cy.baseVal.value = 25;
shape.r.baseVal.value = 20;
shape.setAttribute("fill", "green");
document.documentElement.appendChild(shape);
You can't do it in pure Lua without eating CPU, but there's a simple, non-portable way:
os.execute("sleep 1")
(it will block)
Obviously, this only works on operating systems for which "sleep 1" is a valid command, for instance Unix, but not Windows.
Need some adjusts but should work for Express v4. Including those routes added with .use()
.
function listRoutes(routes, stack, parent){
parent = parent || '';
if(stack){
stack.forEach(function(r){
if (r.route && r.route.path){
var method = '';
for(method in r.route.methods){
if(r.route.methods[method]){
routes.push({method: method.toUpperCase(), path: parent + r.route.path});
}
}
} else if (r.handle && r.handle.name == 'router') {
const routerName = r.regexp.source.replace("^\\","").replace("\\/?(?=\\/|$)","");
return listRoutes(routes, r.handle.stack, parent + routerName);
}
});
return routes;
} else {
return listRoutes([], app._router.stack);
}
}
//Usage on app.js
const routes = listRoutes(); //array: ["method: path", "..."]
edit: code improvements
Only in theoretical case, when hashcodes are always different and bucket for every hash code is also different, the O(1) will exist. Otherwise, it is of constant order i.e. on increment of hashmap, its order of search remains constant.
If you need by several params:
$ids = [1,2,3,4];
$not_ids = [5,6,7,8];
DB::table('table')->whereIn('id', $ids)
->whereNotIn('id', $not_ids)
->where('status', 1)
->get();
Most of these linker errors occur because of missing libraries.
I added the libstdc++.6.dylib in my Project->Targets->Build Phases-> Link Binary With Libraries.
That solved it for me on Xcode 6.3.2 for iOS 8.3
Cheers!
A complete solution in swift, in your view controller
// you can use your own logic to determine if you need to hide status bar
// I just put a var here for now
var hideStatusBar = false
override func preferStatusBarHidden() -> Bool {
return hideStatus
}
// in other method to manually toggle status bar
func updateUI() {
hideStatusBar = true
// call this method to update status bar
prefersStatusBarHidden()
}
I believe this line in the web.config will set the max upload size:
<system.web>
<httpRuntime maxRequestLength="600000"/>
</system.web>
If you have an ASP.NET / ASP.NET MVC application, you can include this header via the Web.config file:
<system.webServer>
...
<httpProtocol>
<customHeaders>
<!-- Enable Cross Domain AJAX calls -->
<remove name="Access-Control-Allow-Origin" />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
import os
import tempfile
path = tempfile.mktemp(dir=path)
os.makedirs(path)
os.rmdir(path)
I don't think you can mount a Linux folder as a network drive under windows having only access to ssh. I can suggest you to use WinSCP that allows you to transfer file through ssh and it's free.
EDIT: well, sorry. Vinko posted before me and now i've learned a new thing :)
A developer recently added subtitle support to VideoView.
When the MediaPlayer
starts playing a music (or other source), it checks if there is a SubtitleController and shows this message if it's not set.
It doesn't seem to care about if the source you want to play is a music or video. Not sure why he did that.
Short answer: Don't care about this "Exception".
Edit :
Still present in Lollipop,
If MediaPlayer
is only used to play audio files and you really want to remove these errors in the logcat, the code bellow set an empty SubtitleController
to the MediaPlayer
.
It should not be used in production environment and may have some side effects.
static MediaPlayer getMediaPlayer(Context context){
MediaPlayer mediaplayer = new MediaPlayer();
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
return mediaplayer;
}
try {
Class<?> cMediaTimeProvider = Class.forName( "android.media.MediaTimeProvider" );
Class<?> cSubtitleController = Class.forName( "android.media.SubtitleController" );
Class<?> iSubtitleControllerAnchor = Class.forName( "android.media.SubtitleController$Anchor" );
Class<?> iSubtitleControllerListener = Class.forName( "android.media.SubtitleController$Listener" );
Constructor constructor = cSubtitleController.getConstructor(new Class[]{Context.class, cMediaTimeProvider, iSubtitleControllerListener});
Object subtitleInstance = constructor.newInstance(context, null, null);
Field f = cSubtitleController.getDeclaredField("mHandler");
f.setAccessible(true);
try {
f.set(subtitleInstance, new Handler());
}
catch (IllegalAccessException e) {return mediaplayer;}
finally {
f.setAccessible(false);
}
Method setsubtitleanchor = mediaplayer.getClass().getMethod("setSubtitleAnchor", cSubtitleController, iSubtitleControllerAnchor);
setsubtitleanchor.invoke(mediaplayer, subtitleInstance, null);
//Log.e("", "subtitle is setted :p");
} catch (Exception e) {}
return mediaplayer;
}
This code is trying to do the following from the hidden API
SubtitleController sc = new SubtitleController(context, null, null);
sc.mHandler = new Handler();
mediaplayer.setSubtitleAnchor(sc, null)
You have not defined the variable input_line
.
Add this:
string input_line;
And add this include.
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}
They're essentially the same, if your program is run from an interactive prompt and you haven't redirected stdin or stdout:
public class ConsoleTest {
public static void main(String[] args) {
System.out.println("Console is: " + System.console());
}
}
results in:
$ java ConsoleTest
Console is: java.io.Console@2747ee05
$ java ConsoleTest </dev/null
Console is: null
$ java ConsoleTest | cat
Console is: null
The reason Console
exists is to provide features that are useful in the specific case that you're being run from an interactive command line:
Console
will queue them up nicely, whereas if you used System.in/out then all of the prompts would appear simultaneously).Notice above that redirecting even one of the streams results in System.console()
returning null
; another irritation is that there's often no Console
object available when spawned from another program such as Eclipse or Maven.
A few points:
1) "DataBind()" is only for web apps (not windows apps).
2) Your code looks very 'JAVAish' (not a bad thing, just an observation).
Try this:
mnuActionLanguage.ComboBox.DataSource = languages;
If that doesn't work... then I'm assuming that your datasource is being stepped on somewhere else in the code.
import sys
sys.modules.keys()
An approximation of getting all imports for the current module only would be to inspect globals()
for modules:
import types
def imports():
for name, val in globals().items():
if isinstance(val, types.ModuleType):
yield val.__name__
This won't return local imports, or non-module imports like from x import y
. Note that this returns val.__name__
so you get the original module name if you used import module as alias
; yield name instead if you want the alias.
#include <iostream>
#include <string>
#include <vector>
#include <boost/assign/list_of.hpp>
int main()
{
const std::vector< std::string > v = boost::assign::list_of( "abc" )( "xyz" );
std::copy(
v.begin(),
v.end(),
std::ostream_iterator< std::string >( std::cout, "\n" ) );
}
I would do
import os
path = os.path.normpath(path)
path.split(os.sep)
First normalize the path string into a proper string for the OS. Then os.sep
must be safe to use as a delimiter in string function split.
If you want to avoid the error message and you are not using Bootstrap tool tips, you can define window.Tether before loading Bootstrap.
<script>
window.Tether = {};
</script>
<script src="js/bootstrap.min.js"></script>
In my case it was caused by align_parentBottom="true"
given to a view inside a RelativeLayout
. Removed all the alignParentBottom's and changed all the layouts to vertical LinearLayouts and problem gone.
subset()
is also useful:
subset(DATAFRAME, COLUMNNAME == "")
For a survey package, maybe the survey
package is pertinent?
Instead of using a UIView
, as @ImreKelényi suggests, you can use a CALayer
:
// Add a bottomBorder.
CALayer *bottomBorder = [CALayer layer];
bottomBorder.frame = CGRectMake(0.0f, 43.0f, toScrollView.frame.size.width, 1.0f);
bottomBorder.backgroundColor = [UIColor colorWithWhite:0.8f
alpha:1.0f].CGColor;
[toScrollView.layer addSublayer:bottomBorder];
If you don't want hashes and just the first lines (subject lines):
git log --pretty=format:%s
SWIFT 4+ Answer
iPhone X, XR, XS, XSMAX, 11 Pro, 11 Pro Max:
Note: Need real device for test
let deviceType = UIDevice.current.modelName
switch deviceType {
case "iPhone10,3", "iPhone10,6":
print("iPhoneX")
case "iPhone11,2":
print("iPhone XS")
case "iPhone11,4":
print("iPhone XS Max")
case "iPhone11,6":
print("iPhone XS Max China")
case "iPhone11,8":
print("iPhone XR")
case "iPhone12,3":
print("iPhone 11 Pro")
case "iPhone12,5":
print("iPhone 11 Pro Max")
default:
break
}
extension UIDevice {
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
return identifier
}
}