I had the same issues even after running all those EXEC stored procedure commands that you see on every answer/blog, but when I ran SSMS as administrator, the problems went away. Since, I didn't want to do that, I opened Services, went to SQL Server (MyServer), right clicked, selected properties. On the Log On tab, "This account:" was selected with and listed my SQL Server account/password. I instead checked "Local System account" and ticked the "Allow service to interact with desktop". Then I stopped and started the service. Now, I can run the same query as the original poster mentions without running as administrator in SSMS. This probably worked because I am running SQL Server on my home desktop.
I'd also like to point out that you can use GUI in SSMS to enable adhoc access (and many other options). In SSMS, go to Linked Servers>Providers, right click on the provider, and select properties. Then you can just check/uncheck the ones you want.
If you would like a software tool to do this, you might like to check out this step-by-step guide:
"How to Validate and Import Excel spreadsheet to SQL Server database"
I had this same problem and it seemed to be related to using the same database connection for concurrent tasks. There might be some alternative solutions (maybe better), but I solved it by setting MaxConcurrentExecutables
to 1.
If ad hoc updates to system catalog is "not supported", or if you get a "Msg 5808" then you will need to configure with override like this:
EXEC sp_configure 'show advanced options', 1
RECONFIGURE with override
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE with override
GO
Ran into this issue where the linked server would work for users who were local admins on the server, but not for anyone else. After many hours of messing around, I managed to fix the problem using the following steps:
So, I was having the same issue. The main reason I am installing Appfabric is to create a SharePoint 2013 development server.
What did not work:
What worked for me to get Appfrabic installed was installing from the setup file via powershell. Woo hoo! It worked for me! This is the link I retrieved the commands from: Installing AppFabric 1.1 with PowerShell DSC results in modal dialog error
Start-Process -FilePath 'c:\temp\SharePoint\pre\appfabric\setup.exe' -ArgumentList '/i cacheclient","cachingService","CacheAdmin /gac /l c:\temp\appfabric.log' -Wait | Write-verbose
Start-Process -FilePath 'c:\temp\SharePoint\pre\AppFabric1.1-RTM-KB2671763-x64-ENU.exe' -ArgumentList '/quiet' -Wait | Write-verbose
I hope this helps others with the same issue.
I think this is closer to the answer you're looking for:
<input type="file">
$file = $(file);
var filename = fileElement[0].files[0].name;
Create PROCEDURE Stored_Procedure_Name_2
(
@param1 int = 5 ,
@param2 varchar(max),
@param3 varchar(max)
)
AS
DECLARE @Table TABLE
(
/*TABLE DEFINITION*/
id int,
name varchar(max),
address varchar(max)
)
INSERT INTO @Table
EXEC Stored_Procedure_Name_1 @param1 , @param2 = 'Raju' ,@param3 =@param3
SELECT id ,name ,address FROM @Table
Here is one possible way of doing this based on the assumption that there will not be any blank sheets in the Excel files and also all the sheets follow the exact same structure. Also, under the assumption that the file extension is only .xlsx
Following example was created using SSIS 2008 R2 and Excel 2007. The working folder for this example is F:\Temp\
In the folder path F:\Temp\
, create an Excel 2007 spreadsheet file named States_1.xlsx
with two worksheets.
Sheet 1
of States_1.xlsx contained the following data
Sheet 2
of States_1.xlsx contained the following data
In the folder path F:\Temp\
, create another Excel 2007 spreadsheet file named States_2.xlsx
with two worksheets.
Sheet 1
of States_2.xlsx contained the following data
Sheet 2
of States_2.xlsx contained the following data
Create a table in SQL Server named dbo.Destination using the below create script. Excel sheet data will be inserted into this table.
CREATE TABLE [dbo].[Destination](
[Id] [int] IDENTITY(1,1) NOT NULL,
[State] [nvarchar](255) NULL,
[Country] [nvarchar](255) NULL,
[FilePath] [nvarchar](255) NULL,
[SheetName] [nvarchar](255) NULL,
CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO
The table is currently empty.
Create a new SSIS package and on the package, create the following 4 variables. FolderPath will contain the folder where the Excel files are stored. FilePattern will contain the extension of the files that will be looped through and this example works only for .xlsx
. FilePath will be assigned with a value by the Foreach Loop container but we need a valid path to begin with for design time and it is currently populated with the path F:\Temp\States_1.xlsx
of the first Excel file. SheetName will contain the actual sheet name but we need to populate with initial value Sheet1$
to avoid design time error.
In the package's connection manager, create an ADO.NET connection with the following configuration and name it as ExcelSchema.
Select the provider Microsoft Office 12.0 Access Database Engine OLE DB Provider
under .Net Providers for OleDb. Provide the file path F:\Temp\States_1.xlsx
Click on the All
section on the left side and set the property Extended Properties to Excel 12.0
to denote the version of Excel. Here in this case 12.0 denotes Excel 2007
. Click on the Test Connection to make sure that the connection succeeds.
Create an Excel connection manager named Excel as shown below.
Create an OLE DB Connection SQL Server named SQLServer
. So, we should have three connections on the package as shown below.
We need to do the following connection string changes so that the Excel file is dynamically changed as the files are looped through.
On the connection ExcelSchema, configure the expression ServerName
to use the variable FilePath
. Click on the ellipsis button to configure the expression.
Similarly on the connection Excel, configure the expression ServerName
to use the variable FilePath
. Click on the ellipsis button to configure the expression.
On the Control Flow, place two Foreach Loop containers one within the other. The first Foreach Loop container
named Loop files will loop through the files. The second Foreach Loop container
will through the sheets within the container. Within the inner For each loop container, place a Data Flow Task that will read the Excel files and load data into SQL
Configure the first Foreach loop container named Loop files as shown below:
Configure the first Foreach loop container named Loop sheets as shown below:
Inside the data flow task, place an Excel Source, Derived Column and OLE DB Destination as shown below:
Configure the Excel Source to read the appropriate Excel file and the sheet that is currently being looped through.
Configure the derived column to create new columns for file name and sheet name. This is just to demonstrate this example but has no significance.
Configure the OLE DB destination to insert the data into the SQL table.
Below screenshot shows successful execution of the package.
Below screenshot shows that data from the 4 workbooks in 2 Excel spreadsheets that were creating in the beginning of this answer is correctly loaded into the SQL table dbo.Destination.
Hope that helps.
If you're executing the query and expecting a ResultSet
(you are in this scenario, at least) then you can simply call ResultSet
's getStatement()
like so:
ResultSet rs = pstmt.executeQuery();
String executedQuery = rs.getStatement().toString();
The variable executedQuery
will contain the statement that was used to create the ResultSet
.
Now, I realize this question is quite old, but I hope this helps someone..
You could always construct the #temp table in dynamic SQL. For example, right now I guess you have been trying:
CREATE TABLE #tmp(a INT, b INT, c INT);
DECLARE @sql NVARCHAR(1000);
SET @sql = N'BULK INSERT #tmp ...' + @variables;
EXEC master.sys.sp_executesql @sql;
SELECT * FROM #tmp;
This makes it tougher to maintain (readability) but gets by the scoping issue:
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'CREATE TABLE #tmp(a INT, b INT, c INT);
BULK INSERT #tmp ...' + @variables + ';
SELECT * FROM #tmp;';
EXEC master.sys.sp_executesql @sql;
EDIT 2011-01-12
In light of how my almost 2-year old answer was suddenly deemed incomplete and unacceptable, by someone whose answer was also incomplete, how about:
CREATE TABLE #outer(a INT, b INT, c INT);
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'SET NOCOUNT ON;
CREATE TABLE #inner(a INT, b INT, c INT);
BULK INSERT #inner ...' + @variables + ';
SELECT * FROM #inner;';
INSERT #outer EXEC master.sys.sp_executesql @sql;
Apparently Chrome and Safari are wrong: onchange
should only be triggered when the user releases the mouse. To get continuous updates, you should use the oninput
event, which will capture live updates in Firefox, Safari and Chrome, both from the mouse and the keyboard.
However, oninput
is not supported in IE10, so your best bet is to combine the two event handlers, like this:
<span id="valBox"></span>
<input type="range" min="5" max="10" step="1"
oninput="showVal(this.value)" onchange="showVal(this.value)">
Check out this Bugzilla thread for more information.
I know this is old but for anyone coming to this for an answer you would do it like so:
Overflow hidden on a element containing the parent element, such as the body.
Give your child element a width much wider than your page, and position it absolute left by -100%.
Heres an example:
body {
overflow:hidden;
}
.parent{
width: 960px;
background-color: red;
margin: 0 auto;
position: relative;
}
.child {
height: 200px;
position: absolute;
left: -100%;
width:9999999px;
}
Also heres a JS Fiddle: http://jsfiddle.net/v2Tja/288/
SELECT *
FROM sys.objects
WHERE type = 'V'
There's also MoSync Mobile SDK
GPL and commercial licensing. There's a good overview of their approach here.
You can use HTTP Requests that are described in the Requests: HTTP for Humans user guide.
Another way is to use an array as a type, e.g.:
ObjectMapper objectMapper = new ObjectMapper();
MyPojo[] pojos = objectMapper.readValue(json, MyPojo[].class);
This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list by:
List<MyPojo> pojoList = Arrays.asList(pojos);
IMHO this is much more readable.
And to make it be an actual list (that can be modified, see limitations of Arrays.asList()
) then just do the following:
List<MyPojo> mcList = new ArrayList<>(Arrays.asList(pojos));
Assertions are generally used primarily as a means of checking the program's expected behavior. It should lead to a crash in most cases, since the programmer's assumptions about the state of the program are false. This is where the debugging aspect of assertions come in. They create a checkpoint that we simply can't ignore if we would like to have correct behavior.
In your case it does data validation on the incoming parameters, though it does not prevent clients from misusing the function in the future. Especially if they are not, (and should not) be included in release builds.
Since this is the first hit on Google searching for "intelliJ cannot find symbol" error, I'm gonna throw in my solution as well.
The problem for me was that my project originated from Eclipse, and some files contained dependency on classes that were generated in src/generated-sources
by specifications in pom.xml. For some reason, this was not properly executed when I first opened the project and rebuilding/re-importing did not help, so the files were never generated.
The solution was to right-click on the module, and select Maven -> Generate Sources and Update Folders
That solved the issue and I could compile.
Had a similar situation myself. I think it is best to create the tar elsewhere and then use -C to tell tar the base directory for the compressed files. Example:
tar -cjf workspace.tar.gz -C <path_to_workspace> $(ls -A <path_to_workspace>)
This way there is no need to exclude your own tarfile. As noted in other comments, -A will list hidden files.
The only thing that worked for me:
g.drawOval((getWidth()-200)/2,(getHeight()-200)/2, 200, 200);
There is no way to store objects in SharedPreferences, What i did is to create a public class, put all the parameters i need and create setters and getters, i was able to access my objects,
The above works,(having an original document with mixed pages of 11' and 16' wide). However auto rotate needs to be off otherwise landscape pages are saved with page white top and bottom, so dont work in full screen view.
Solution is to re open the new PDF in acrobat and crop the first image (carefully to avoid white border), then select page range i.e. all, this then applies to all pages. job done !
I had PHP7.2 on a Ubuntu 16.04 server and it solved my problem:
sudo apt-get install zip unzip php-zip
Update
Tried this for Ubuntu 18.04 and worked as well.
That's a difficult problem to solve since visually similar PDFs may have a wildly differing structure depending on how they were produced. In the worst case the library would need to basically act like an OCR. On the other hand, the PDF may contain sufficient structure and metadata for easy removal of tables and figures, which the library can be tailored to take advantage of.
I'm pretty sure there are no open source tools which solve your problem for a wide variety of PDFs, but I remember having heard of commercial software claiming to do exactly what you ask for. I'm sure you'll run into them while googling.
No, React doesn't render everything when the state changes.
Whenever a component is dirty (its state changed), that component and its children are re-rendered. This, to some extent, is to re-render as little as possible. The only time when render isn't called is when some branch is moved to another root, where theoretically we don't need to re-render anything. In your example, TimeInChild
is a child component of Main
, so it also gets re-rendered when the state of Main
changes.
React doesn't compare state data. When setState
is called, it marks the component as dirty (which means it needs to be re-rendered). The important thing to note is that although render
method of the component is called, the real DOM is only updated if the output is different from the current DOM tree (a.k.a diffing between the Virtual DOM tree and document's DOM tree). In your example, even though the state
data hasn't changed, the time of last change did, making Virtual DOM different from the document's DOM, hence why the HTML is updated.
Actually this would go faster in most of cases:
SELECT *
FROM table ta1
JOIN table ta2 on ta1.id != ta2.id
WHERE ta1.c2 = ta2.c2 and ta1.c3 = ta2.c3 and ta1.c4 = ta2.c4
You join on different rows which have the same values. I think it should work. Correct me if I'm wrong.
You will simply need to do a type check for each of the basic numeric types.
Here's an extension method that should do the job:
public static bool IsNumber(this object value)
{
return value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is int
|| value is uint
|| value is long
|| value is ulong
|| value is float
|| value is double
|| value is decimal;
}
This should cover all numeric types.
It seems you do actually want to parse the number from a string during deserialisation. In this case, it would probably just be best to use double.TryParse
.
string value = "123.3";
double num;
if (!double.TryParse(value, out num))
throw new InvalidOperationException("Value is not a number.");
Of course, this wouldn't handle very large integers/long decimals, but if that is the case you just need to add additional calls to long.TryParse
/ decimal.TryParse
/ whatever else.
I believe the simplest answer is
list.reduce(:+).to_f / list.size
In my case it works only with two line of code. Test the below C# code:
String dirPath = "C:\myfolder\";
String imgName = "my_mage_name.bmp";
byte[] imgByteArray = Convert.FromBase64String("your_base64_string");
File.WriteAllBytes(dirPath + imgName, imgByteArray);
That's it. Kindly up vote if you really find this solution works for you. Thanks in advance.
import * as utils from './utils.js';
If you do the above, you will be able to use functions in utils.js as
utils.someFunction()
Try this:
layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
and for API 16<:
layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready));
It's the same way you run it from command line. Just put that "command line" into a ".bat" file.
So, if you use java -cp .;foo.jar Bar
, put that into a .bat file as
@echo off
java -cp .;foo.jar Bar
#For Unable to 'apt update' my Ubuntu 19.04
The repositories for older releases that are not supported (like 11.04, 11.10 and 13.04) get moved to an archive server. There are repositories available at http://old-releases.ubuntu.com.
first break up this file
cp /etc/apt/sources.list /etc/apt/sources.list.bak sudo sed -i -re 's/([a-z]{2}.)?archive.ubuntu.com|security.ubuntu.com/old-releases.ubuntu.com/g' /etc/apt/sources.list
then
sudo apt-get update && sudo apt-get dist-upgrade
I got this error when trying to create a new Eclipse project inside a newly cloned Git repo folder.
This worked for me:
1) clone the Git repo (in my case it was to a subfolder of the Eclipse default workspace)
2) create the new Eclipse project in the default workspace (one level above the cloned Git repo folder)
3) export the new Eclipse project from the default workspace to the cloned repo directory:
a) right click on project --> Export --> General --> File System
b) select the new Eclipse project
c) set the destination directory to export to (as the Git repo folder)
4) remove the Eclipse project form the workspace (because it's still the one that uses the default workspace)
right click on project and select "Delete"
5) open the exported Eclipse project from inside the Git repo directory
a) File --> Open Project from File System or Archive
b) set the "Import source" folder as the Git repo folder
c) check the project to import (that you just exported there)
Yes, you can hide only the rows that you want to hide. This can be helpful if you want to show rows only when some condition is satisfied in the rows that are currently being shown. The following worked for me.
<table>
<tr><th>Sample Table</th></tr>
<tr id="row1">
<td><input id="data1" type="text" name="data1" /></td>
</tr>
<tr id="row2" style="display: none;">
<td><input id="data2" type="text" name="data2" /></td>
</tr>
<tr id="row3" style="display: none;">
<td><input id="data3" type="text" name="data3" /></td>
</tr>
</table>
In CSS, do the following:
#row2{
display: none;
}
#row3{
display: none;
}
In JQuery, you might have something like the following to show the desired rows.
$(document).ready(function(){
if($("#row1").val() === "sometext"){ //your desired condition
$("#row2").show();
}
if($("#row2").val() !== ""){ //your desired condition
$("#row3").show();
}
});
Swift 3:
//This gives month as three letters (Jun, Dec, etc)
let justMonth = DateFormatter()
justMonth.dateFormat = "MMM"
myFirstLabel.text = justMonth.string(from: myDate)
//This gives the day of month, with no preceding 0s (6,14,29)
let justDay = DateFormatter()
justDay.dateFormat = "d"
mySecondLabel.text = justDay.string(from: myDate)
//This gives year as two digits, preceded by an apostrophe ('09, '16, etc)
let justYear = DateFormatter()
justYear.dateFormat = "yy"
myThirdLabel.text = "'\(justYear.string(from: lastCompDate))"
For more formats, check out this link to a codingExplorer table with all the available formats. Each date component has several options, for example:
Year:
Pretty much every component has 2-4 options, using the first letter to express the format (day is "d", hour is "h", etc). However, month is a capital "M", because the lower case "m" is reserved for minute. There are some other exceptions though, so check out the link!
Try calling the image in a <DIV>
tag, which will allow a smoother and faster loading time. Take note that because this is a background image, you can also put text over the image between the <DIV></DIV>
tags. This works great for custom store/shop listings as well...to post a cool " Sold Out! " overlay, or whatever you might want.
Here is the pic/text- sided by side version, which can be used for blog post and article listing:
<div class="whatever_container">
<h2>Title/Header Here</h2>
<div id="image-container-name"style="background-image:url('images/whatever-this-is-named.jpg');background color:#FFFFFF;height:75px;width:20%;float:left;margin:0px 25px 0px 5px;"></div>
<p>All of your text goes here next to the image.</p></div>
Check if this solves the problem:
<div class="container-fluid no-padding">
<div class="row">
<div class="col-md-12">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=1300%C3%97400&w=1300&h=400" alt="placeholder 960" class="img-responsive" />
</div>
</div>
</div>
CSS
.no-padding {
padding-left: 0;
padding-right: 0;
}
Css class no-padding
will override default bootstrap container padding.
Full example here.
@Update If you use bootstrap 4 it could be done even simpler
<div class="container-fluid px-0">
<div class="row">
<div class="col-md-12">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=1300%C3%97400&w=1300&h=400" alt="placeholder 960" class="img-responsive" />
</div>
</div>
</div>
Updated example here.
-O
is the option to specify the path of the file you want to download to:
wget <uri> -O /path/to/file.ext
-P
is prefix where it will download the file in the directory:
wget <uri> -P /path/to/folder
The state of the checkbox will be reflected on whatever model you have it bound to, in this case, $scope.answers[item.questID]
Another more manual option to get it:
.nuget\nuget.exe install Newtonsoft.Json -Version 4.0.5
To get the insert ignore logic you can do something like below. I found simply inserting from a select statement of literal values worked best, then you can mask out the duplicate keys with a NOT EXISTS clause. To get the update on duplicate logic I suspect a pl/pgsql loop would be necessary.
INSERT INTO manager.vin_manufacturer
(SELECT * FROM( VALUES
('935',' Citroën Brazil','Citroën'),
('ABC', 'Toyota', 'Toyota'),
('ZOM',' OM','OM')
) as tmp (vin_manufacturer_id, manufacturer_desc, make_desc)
WHERE NOT EXISTS (
--ignore anything that has already been inserted
SELECT 1 FROM manager.vin_manufacturer m where m.vin_manufacturer_id = tmp.vin_manufacturer_id)
)
It's not an error. Javascript will gladly convert a number to a string when a string is expected (for example parseInt(42)
), but in this case there is nothing that expect the number to be a string.
Here's a makeLowerCase
function. :)
function makeLowerCase(value) {
return value.toString().toLowerCase();
}
I got the same Problem:
g++ -mconsole -Wl,--export-all-symbols -LC:/Programme/CPP-Entwicklung/MinGW-4.5.2/lib -LD:/bfs_ENTW_deb/lib -static-libgcc -static-libstdc++ -LC:/Programme/CPP-Entwicklung/boost_1_47_0/stage/lib \
D:/bfs_ENTW_deb/obj/test/main_filesystem.obj \
-o D:/bfs_ENTW_deb/bin/filesystem.exe -lboost_system-mgw45-mt-1_47 -lboost_filesystem-mgw45-mt-1_47
D:/bfs_ENTW_deb/obj/test/main_filesystem.obj:main_filesystem.cpp:(.text+0x54): undefined reference to `boost::system::generic_category()
Solution was to use the debug-version of the system-lib:
g++ -mconsole -Wl,--export-all-symbols -LC:/Programme/CPP-Entwicklung/MinGW-4.5.2/lib -LD:/bfs_ENTW_deb/lib -static-libgcc -static-libstdc++ -LC:/Programme/CPP-Entwicklung/boost_1_47_0/stage/lib \
D:/bfs_ENTW_deb/obj/test/main_filesystem.obj \
-o D:/bfs_ENTW_deb/bin/filesystem.exe -lboost_system-mgw45-mt-d-1_47 -lboost_filesystem-mgw45-mt-1_47
But why?
assuming that string1 is your whole operation
use mdas
double result;
string recurAndCheck(string operation){
if(operation.indexOf("/")){
String leftSide = recurAndCheck(operation.split("/")[0]);
string rightSide = recurAndCheck(operation.split("/")[1]);
result = Double.parseDouble(leftSide)/Double.parseDouble(rightSide);
} else if (..continue w/ *...) {
//same as above but change / with *
} else if (..continue w/ -) {
//change as above but change with -
} else if (..continuew with +) {
//change with add
} else {
return;
}
}
If you are searching for a property, then "no". You want:
if ('prop' in obj) { }
In general, you should not care whether or not the property comes from the prototype or the object.
However, because you used 'key' in your sample code, it looks like you are treating the object as a hash, in which case your answer would make sense. All of the hashes keys would be properties in the object, and you avoid the extra properties contributed by the prototype.
John Resig's answer was very comprehensive, but I thought it wasn't clear. Especially with when to use "'prop' in obj".
A free windows app that does that
http://www.addictivetips.com/windows-tips/csv-splitter-for-windows/
to convert the current datetime to file name to save files you can use
DateTime.Now.ToFileTime();
this should resolve your objective
You can set the type of error reporting you need in php.ini or by using the error_reporting() function on top of your script.
So this solution takes a string as its parameter. It finds how many rows are in the sheet. It gets all the values in the column specified. It loops through the values from the end to the beginning until it finds a value that is not an empty string. Finally it retunrs the value.
Script:
function lastValue(column) {
var lastRow = SpreadsheetApp.getActiveSheet().getMaxRows();
var values = SpreadsheetApp.getActiveSheet().getRange(column + "1:" + column + lastRow).getValues();
for (; values[lastRow - 1] == "" && lastRow > 0; lastRow--) {}
return values[lastRow - 1];
}
Usage:
=lastValue("G")
EDIT:
In response to the comment asking for the function to update automatically:
The best way I could find is to use this with the code above:
function onEdit(event) {
SpreadsheetApp.getActiveSheet().getRange("A1").setValue(lastValue("G"));
}
It would no longer be required to use the function in a cell like the Usage section states. Instead you are hard coding the cell you would like to update and the column you would like to track. It is possible that there is a more eloquent way to implement this (hopefully one that is not hard coded), but this is the best I could find for now.
Note that if you use the function in cell like stated earlier, it will update upon reload. Maybe there is a way to hook into onEdit()
and force in cell functions to update. I just can't find it in the documentation.
FormName.WindowState = FormWindowState.Minimized;
Please follow the steps below :
Based on 4 and 5, execute one of the commands (Do not execute all of them without reading above description):
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
sudo xcode-select -s /Applications/Xcode-beta.app/Contents/Developer
sudo xcode-select -s /[XCODE-ACTUAL-LOCATION]/Xcode.app/Contents/Developer
sudo xcode-select -s /[XCODE-ACTUAL-LOCATION]/Xcode-beta.app/Contents/Developer
Import connect
from react-redux
and use it to connect the component with the state connect(mapStates,mapDispatch)(component)
import React from "react";
import { connect } from "react-redux";
const MyComponent = (props) => {
return (
<div>
<h1>{props.title}</h1>
</div>
);
}
}
Finally you need to map the states to the props to access them with this.props
const mapStateToProps = state => {
return {
title: state.title
};
};
export default connect(mapStateToProps)(MyComponent);
Only the states that you map will be accessible via props
Check out this answer: https://stackoverflow.com/a/36214059/4040563
For further reading : https://medium.com/@atomarranger/redux-mapstatetoprops-and-mapdispatchtoprops-shorthand-67d6cd78f132
You can also do:
array = numpy.append(array, value)
Note that the numpy.append()
method returns a new object, so if you want to modify your initial array, you have to write: array = ...
I found the following which seems to accomplish this: https://github.com/mennovanslooten/Observable-Arrays
Observable-Arrays extends underscore and can be used as follow: (from that page)
// For example, take any array:
var a = ['zero', 'one', 'two', 'trhee'];
// Add a generic observer function to that array:
_.observe(a, function() {
alert('something happened');
});
To solve your other problem, where you need to set scrolled
if the user scrolls manually, you'd have to attach a handler to the window scroll event. Generally this is a bad idea as the handler will fire a lot, a common technique is to set a timeout, like so:
var timer = 0;
$(window).scroll(function() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
scrolled = $(window).scrollTop();
}, 250);
});
In my case, because I had reinstalled iis, I needed to register iis with dot net 4 using this command:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
The easiest way is to use the replace
method on the column. The arguments are a list of the things you want to replace (here ['ABC', 'AB']
) and what you want to replace them with (the string 'A'
in this case):
>>> df['BrandName'].replace(['ABC', 'AB'], 'A')
0 A
1 B
2 A
3 D
4 A
This creates a new Series of values so you need to assign this new column to the correct column name:
df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')
In my apache error log, I saw:
[Tue Feb 16 14:55:02 2010] [notice] child pid 9985 exit signal File size limit exceeded (25)
So I, removed all the contents of my largest log file 2.1GB /var/log/system.log. Now everything works.
>>> df
Station ID Pollutants
0 8809 {"a": "46", "b": "3", "c": "12"}
1 8810 {"a": "36", "b": "5", "c": "8"}
2 8811 {"b": "2", "c": "7"}
3 8812 {"c": "11"}
4 8813 {"a": "82", "c": "15"}
speed comparison for a large dataset of 10 million rows
>>> df = pd.concat([df]*100000).reset_index(drop=True)
>>> df = pd.concat([df]*20).reset_index(drop=True)
>>> print(df.shape)
(10000000, 2)
def apply_drop(df):
return df.join(df['Pollutants'].apply(pd.Series)).drop('Pollutants', axis=1)
def json_normalise_drop(df):
return df.join(pd.json_normalize(df.Pollutants)).drop('Pollutants', axis=1)
def tolist_drop(df):
return df.join(pd.DataFrame(df['Pollutants'].tolist())).drop('Pollutants', axis=1)
def vlues_tolist_drop(df):
return df.join(pd.DataFrame(df['Pollutants'].values.tolist())).drop('Pollutants', axis=1)
def pop_tolist(df):
return df.join(pd.DataFrame(df.pop('Pollutants').tolist()))
def pop_values_tolist(df):
return df.join(pd.DataFrame(df.pop('Pollutants').values.tolist()))
>>> %timeit apply_drop(df.copy())
1 loop, best of 3: 53min 20s per loop
>>> %timeit json_normalise_drop(df.copy())
1 loop, best of 3: 54.9 s per loop
>>> %timeit tolist_drop(df.copy())
1 loop, best of 3: 6.62 s per loop
>>> %timeit vlues_tolist_drop(df.copy())
1 loop, best of 3: 6.63 s per loop
>>> %timeit pop_tolist(df.copy())
1 loop, best of 3: 5.99 s per loop
>>> %timeit pop_values_tolist(df.copy())
1 loop, best of 3: 5.94 s per loop
+---------------------+-----------+
| apply_drop | 53min 20s |
| json_normalise_drop | 54.9 s |
| tolist_drop | 6.62 s |
| vlues_tolist_drop | 6.63 s |
| pop_tolist | 5.99 s |
| pop_values_tolist | 5.94 s |
+---------------------+-----------+
df.join(pd.DataFrame(df.pop('Pollutants').values.tolist()))
is the fastest
Trying to do the same thing consistently with arrays and hashes might just be a code smell, but, at the risk of my being branded as a codorous half-monkey-patcher, if you're looking for consistent behaviour, would this do the trick?:
class Hash
def each_pairwise
self.each { | x, y |
yield [x, y]
}
end
end
class Array
def each_pairwise
self.each_with_index { | x, y |
yield [y, x]
}
end
end
["a","b","c"].each_pairwise { |x,y|
puts "#{x} => #{y}"
}
{"a" => "Aardvark","b" => "Bogle","c" => "Catastrophe"}.each_pairwise { |x,y|
puts "#{x} => #{y}"
}
We can use this for text clear
$('input[name="message"]').val("");
_x000D_
As others have said, you do not need internet for GPS.
GPS is basically a satellite based positioning system that is designed to calculate geographic coordinates based on timing information received from multiple satellites in the GPS constellation. GPS has a relatively slow time to first fix (TTFF), and from a cold start (meaning without a last known position), it can take up to 15 minutes to download the data it needs from the satellites to calculate a position. A-GPS used by cellular networks shortens this time by using the cellular network to deliver the satellite data to the phone.
But regardless of whether it is an A-GPS or GPS location, all that is derived is Geographic Coordinates (latitude/longitude). It is impossible to obtain more from GPS only.
To be able to return anything other than coordinates (such as an address), you need some mechanism to do Reverse Geocoding. Typically this is done by querying a server or a web service (like using Google Maps or Bing Maps, but there are others). Some of the services will allow you to cache data locally, but it would still require an internet connection for periods of time to download the map information in the surrounding area.
While it requires a significant amount of effort, you can write your own tool to do the reverse geocoding, but you still need to be able to house the data somewhere as the amount of data required to do this is far more you can store on a phone, which means you still need an internet connection to do it. If you think of tools like Garmin GPS Navigation units, they do store the data locally, so it is possible, but you will need to optimize it for maximum storage and would probably need more than is generally available in a phone.
The short answer to your question is, no you do not need an active internet connection to get coordinates, but unless you are building a specialized device or have unlimited storage, you will need an internet connection to turn those coordinates into anything else.
I had this issue for dependencies that were created in other projects. Downloaded thirdparty dependencies showed up fine in the build path, but not a library that I had created.
SOLUTION: In the project that is not building correctly, right-click on the project and choose Properties, and then Maven. Uncheck the box labeled "Resolve dependencies from Workspace projects", hit Apply, and then OK. Right-click again on your project and do a Maven->Update Snapshots (or Update Dependencies) and your errors should go away when your project rebuilds (automatically if you have auto-build enabled).
Using Boost.Filesystem:
boost::filesystem::path p("C:\\folder\\foo.txt");
boost::filesystem::path dir = p.parent_path();
Choose which DI to inject stuff into Jersey:
Spring 4:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring4</artifactId>
</dependency>
Spring 3:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
</dependency>
HK2:
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
From 5.2.2/2 (character display semantics) :
\b
(backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.
\n
(new line) Moves the active position to the initial position of the next line.
\r
(carriage return) Moves the active position to the initial position of the current line.
Here, your code produces :
<new_line>ab
\b
: back one charactersi
: overrides the b
with s
(producing asi
on the second line)\r
: back at the beginning of the current lineha
: overrides the first two characters (producing hai
on the second line)In the end, the output is :
\nhai
Instead of:
int count = 0;
for (int i = 0; i<args.length -1; ++i)
count++;
System.out.println(count);
}
you can just
int count = args.length;
The average is the sum of your args divided by the number of your args.
int res = 0;
int count = args.lenght;
for (int a : args)
{
res += a;
}
res /= count;
you can make this code shorter too, i'll let you try and ask if you need help!
This is my first answerso tell me if something wrong!
When you want to write more complex ruby scripts, these tools may help:
For example:
They give you a quick start to write your own scripts, especially 'command line app'.
In my opinion, the easiest way to setup the local locale in python{,3} is:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'de_DE.UTF-8'
Then, locale aware stuff just works, if you're on a decent linux distro, and should work on binary distributions of the other OSes as well (or that's a bug IMHO).
>>> import datetime as dt
>>> print(dt.date.today().strftime("%A %d. %B %Y"))
Sonntag 11. Dezember 2016
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
If you want to SELECT
based on the value of another SELECT
, then you probably want a "subselect":
http://beginner-sql-tutorial.com/sql-subquery.htm
For example, (from the link above):
You want the first and last names from table "student_details" ...
But you only want this information for those students in "science" class:
SELECT id, first_name
FROM student_details
WHERE first_name IN (SELECT first_name
FROM student_details
WHERE subject= 'Science');
Frankly, I'm not sure this is what you're looking for or not ... but I hope it helps ... at least a little...
IMHO...
The simplest way would be to convert your hexadecimal string to a byte array and use the File.WriteAllBytes
method.
Using the StringToByteArray()
method from this question, you'd do something like this:
string hexString = "0CFE9E69271557822FE715A8B3E564BE";
File.WriteAllBytes("output.dat", StringToByteArray(hexString));
The StringToByteArray
method is included below:
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
Regarding the catch 22:
If we use @disabled
, the field is not sent to the action (Mamoud)
And if we use @readonly
, the drop down bug still lets you change the value
Workaround: use @disabled
, and add the field hidden after the drop down:
@Html.HiddenFor(model => model.xxxxxxxx)
Then it is truly disabled, and sent to the to the action too.
WhatsApp has chosen Erlang a language built for writing scalable applications that are designed to withstand errors. Erlang uses an abstraction called the Actor model for it's concurrency - http://en.wikipedia.org/wiki/Actor_(programming_language) Instead of the more traditional shared memory approach, actors communicate by sending each other messages. Actors unlike threads are designed to be lightweight. Actors could be on the same machine or on different machines and the message passing abstractions works for both. A simple implementation of WhatsApp could be: Each user/device is represented as an actor. This actor is responsible for handling the inbox of the user, how it gets serialized to disk, the messages that the user sends and the messages that the user receives. Let's assume that Alice and Bob are friends on WhatsApp. So there is an an Alice actor and a Bob actor.
Let's trace a series of messages flowing back and forth:
Alice decides to message Bob. Alice's phone establishes a connection to the WhatsApp server and it is established that this connection is definitely from Alice's phone. Alice now sends via TCP the following message: "For Bob: A giant monster is attacking the Golden Gate Bridge". One of the WhatsApp front end server deserializes this message and delivers this message to the actor called Alice.
Alice the actor decides to serialize this and store it in a file called "Alice's Sent Messages", stored on a replicated file system to prevent data loss due to unpredictable monster rampage. Alice the actor then decides to forward this message to Bob the actor by passing it a message "Msg1 from Alice: A giant monster is attacking the Golden Gate Bridge". Alice the actor can retry with exponential back-off till Bob the actor acknowledges receiving the message.
Bob the actor eventually receives the message from (2) and decides to store this message in a file called "Bob's Inbox". Once it has stored this message durably Bob the actor will acknowledge receiving the message by sending Alice the actor a message of it's own saying "I received Msg1". Alice the actor can now stop it's retry efforts. Bob the actor then checks to see if Bob's phone has an active connection to the server. It does and so Bob the actor streams this message to the device via TCP.
Bob sees this message and replies with "For Alice: Let's create giant robots to fight them". This is now received by Bob the actor as outlined in Step 1. Bob the actor then repeats Step 2 and 3 to make sure Alice eventually receives the idea that will save mankind.
WhatsApp actually uses the XMPP protocol instead of the vastly superior protocol that I outlined above, but you get the point.
To get the cell value, you need to read it directly from DataGridView1
using e.RowIndex
and e.ColumnIndex
properties.
Eg:
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim value As Object = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
If IsDBNull(value) Then
TextBox1.Text = "" ' blank if dbnull values
Else
TextBox1.Text = CType(value, String)
End If
End Sub
If you don't mind installing an additional light library, you can do this:
pip install plazy
Usage:
import plazy
txt_filter = lambda x : True if x.endswith('.txt') else False
files = plazy.list_files(root='data', filter_func=txt_filter, is_include_root=True)
The result should look something like this:
['data/a.txt', 'data/b.txt', 'data/sub_dir/c.txt']
It works on both Python 2.7 and Python 3.
Github: https://github.com/kyzas/plazy#list-files
Disclaimer: I'm an author of plazy
.
First of all read in the data, then convert it to byte array:
byte b = Byte.parseByte(str, 16);
and then use String
constructor:
new String(byte[] bytes)
or if the charset is not system default then:
new String(byte[] bytes, String charsetName)
This worked for me:
df[,names(df) %in% colnames(df)[grepl(str,colnames(df))]]
I had a similar issue. I had installed PHPMailer version 1.72 which is not prepared to manage SSL connections. Upgrading to last version solved the problem.
No, just include the different fields in the "ON" clause of 1 inner join statement:
SELECT * from Evalulation e JOIN Value v ON e.CaseNum = v.CaseNum
AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum
If your data is already in array form, it's really simple using jQuery:
$(data.msg).each(function()
{
alert(this.value);
alert(this.label);
//this refers to the current item being iterated over
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('#myDropDown').append(option);
});
.ajax()
is more flexible than .getJSON()
- for one, getJson is targeted specifically as a GET request to retrieve json; ajax() can request on any verb to get back any content type (although sometimes that's not useful). getJSON internally calls .ajax().
For angular 4 I have used
<img [src]="data.pic ? data.pic : 'assets/images/no-image.png' " alt="Image" title="Image">
It works for me , I hope it may use to other's also for Angular 4-5
. :)
if you upgraded your Angular Version, you need to change the version of
@angular-devkit/build-angular
inside your
package.json
from your old version to the new angular build version upgraded.
I had upgraded to Angular 10, so i needed to go to https://www.npmjs.com/package/@angular-devkit/build-angular and check which is my version according to Angular 10.
In my case, i founded that the version needs to be 0.1001.7
, so i changed my old version to this version in my package.json and run
npm --save install
That was enough.
As original question was - how to ignore the cert error, here is solution for those using SpringBoot and RestTemplate
@Service
public class SomeService {
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
private static HttpComponentsClientHttpRequestFactory createRequestFactory() {
try {
SSLContextBuilder sslContext = new SSLContextBuilder();
sslContext.loadTrustMaterial(null, new TrustAllStrategy());
CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext.build()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(client);
return requestFactory;
} catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException var3) {
throw new IllegalStateException("Couldn't create HTTP Request factory ignore SSL cert validity: ", var3);
}
}
@Autowired
public SomeService(RestTemplate restTemplate, ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
this.dimetorURL = dimetorURL;
restTemplate.setRequestFactory(createRequestFactory());
}
public ResponseEntity<ResponseObject> sendRequest(RequestObject requestObject) {
//...
return restTemplate.exchange(url, HttpMethod.GET, ResponseObject.class);
//...
}
}
If you’re running JQuery on a production site, which library should you load? JQuery.js or JQuery.min.js? The short answer is, they are essentially the same, with the same functionality.
One version is long, while the other is the minified version. The minified is compressed to save space and page load time. White spaces have been removed in the minified version making them jibberish and impossible to read.
If you’re going to run the JQuery library on a production site, I recommend that you use the minified version, to decrease page load time, which Google now considers in their page ranking.
Another good option is to use Google’s online javascript library. This will save you the hassle of downloading the library, as well as uploading to your site. In addition, your site also does not use resources when JQuery is loaded.
The latest JQuery minified version from Google is available here.
You can link to it in your pages using:
http://ulyssesonline.com/2010/12/03/jquery-js-or-jquery-min-js/
Run command rndc querylog on
or add querylog yes;
to options{};
section in named.conf
to activate that channel.
Also make sure you’re checking correct directory if your bind is chrooted.
This code help me in Attachment sending....
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);
Replace your AddAttachment(...) Code with above code
Most likely .gitignore files are at play. Note that .gitignore files can appear not only at the root level of the repo, but also at any sub level. You might try this from the root level to find them:
find . -name ".gitignore"
and then examine the results to see which might be preventing your subdirs from being added.
There also might be submodules involved. Check the offending directories for ".gitmodules" files.
I had similar requirement (to avoid this ugly ORA-31061: XDB error: special char to escaped char conversion failed. ), but had to keep the line breaks.
I tried this from an excellent comment
'[^ -~|[:space:]]'
but got this ORA-12728: invalid range in regular expression .
but it lead me to my solution:
select t.*, regexp_replace(deta, '[^[:print:]|[:space:]]', '#') from
(select '- <- strangest thing here, and I want to keep line break after
-' deta from dual ) t
displays (in my TOAD tool) as
^
=> is not in the sets (of printing [:print:]
or space |[:space:]
chars)I am Using this
String timeStamp = new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp);
I also faced similar issues when tried to do ng serve. I was able to resolve it as below.
Note:
C:\Windows\system32> is on windows command prompt
C:\apps\workspace\testProj> is on VS code Terminal (can also be doable in another command prompt)
Following are the steps which I used to resolve this.
Step1. Verify the cli version installed on command prompt (will be Angular CLI global version)
C:\Windows\system32>ng --version
Angular CLI: 8.3.13
If cli was installed earlier, it shows the global cli version.
If cli was not installed, we may get the error
ng is not recognized as an internal or external command
a. (Optional Step) Install Angular CLI global version
C:\Windows\system32>npm install -g @angular/cli
C:\Windows\system32>npm install -g @angular-cli/latest
b. Check version again
C:\Windows\system32>ng --version
Angular CLI: 8.3.13
Step2. Verify the local cli version installed on your angular project(VS code ide or command prompt cd'd to your project project)
C:\apps\workspace\testProj>ng --version
Angular CLI: 7.3.8
Note: Clearly versions are not in sync. Do the following in your angular project
C:\apps\workspace\testProj>ng update @angular/cli -> important to sync with global cli version
Note: If upgrade donot work using above command (ref: How to upgrade Angular CLI to the latest version)
On command prompt, uninstall global angular cli, clean the cache and reinstall the cli
C:\Windows\system32>npm uninstall -g angular-cli
C:\Windows\system32>npm cache clean or npm cache verify #(if npm > 5)
C:\Windows\system32>npm install -g @angular/cli@latest
Now update your local project version, because cli version of your local project is having higher priority than global one when you try to execute your project.
C:\apps\workspace\testProj>rm -rf node_modules
C:\apps\workspace\testProj>npm uninstall --save-dev angular-cli
C:\apps\workspace\testProj>npm install --save-dev @angular/cli@latest
C:\apps\workspace\testProj>npm install
C:\apps\workspace\testProj>ng update @angular/cli
Step3. Verify if local project cli version now in sync with global one
C:\Windows\system32>ng --version
Angular CLI: 8.3.13
C:\apps\workspace\testProj>ng --version
Angular CLI: 8.3.13
Step4.. Revalidate on the project
C:\apps\workspace\testProj>ng serve
Should work now
This comes in useful when you have global variables. You declare the existence of global variables in a header, so that each source file that includes the header knows about it, but you only need to “define” it once in one of your source files.
To clarify, using extern int x;
tells the compiler that an object of type int
called x
exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x
to the one definition that it finds in one of the compiled source files. For it to work, the definition of the x
variable needs to have what's called “external linkage”, which basically means that it needs to be declared outside of a function (at what's usually called “the file scope”) and without the static
keyword.
#ifndef HEADER_H
#define HEADER_H
// any source file that includes this will be able to use "global_x"
extern int global_x;
void print_global_x();
#endif
#include "header.h"
// since global_x still needs to be defined somewhere,
// we define it (for example) in this source file
int global_x;
int main()
{
//set global_x here:
global_x = 5;
print_global_x();
}
#include <iostream>
#include "header.h"
void print_global_x()
{
//print global_x here:
std::cout << global_x << std::endl;
}
The C way:
char buf[100];
strcpy(buf, one);
strcat(buf, two);
The C++ way:
std::string buf(one);
buf.append(two);
The compile-time way:
#define one "hello "
#define two "world"
#define concat(first, second) first second
const char* buf = concat(one, two);
While you can store an unlimited number of files/objects in a single bucket, when you go to list a "directory" in a bucket, it will only give you the first 1000 files/objects in that bucket by default. To access all the files in a large "directory" like this, you need to make multiple calls to their API.
tv_nsec
is the sleep time in nanoseconds. 500000us = 500000000ns, so you want:
nanosleep((const struct timespec[]){{0, 500000000L}}, NULL);
New style classes may use super(Foo, self)
where Foo
is a class and self
is the instance.
super(type[, object-or-type])
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.
And in Python 3.x you can simply use super()
inside a class without any parameters.
You should iterate over the keys and get the values using square brackets.
See: How do I enumerate the properties of a javascript object?
EDIT: Obviously, this makes the question a duplicate.
You need to use brackets when using the fileExists
step in an if
condition or assign the returned value to a variable
Using variable:
def exists = fileExists 'file'
if (exists) {
echo 'Yes'
} else {
echo 'No'
}
Using brackets:
if (fileExists('file')) {
echo 'Yes'
} else {
echo 'No'
}
The short answer is, you have to loop.
More info on this topic:
What's the fastest way to copy the values and keys from one dictionary into another in C#?
There are ways to handle your own signals in certain JVMs -- see this article about the HotSpot JVM for example.
By using the Sun internal sun.misc.Signal.handle(Signal, SignalHandler)
method call you are also able to register a signal handler, but probably not for signals like INT
or TERM
as they are used by the JVM.
To be able to handle any signal you would have to jump out of the JVM and into Operating System territory.
What I generally do to (for instance) detect abnormal termination is to launch my JVM inside a Perl script, but have the script wait for the JVM using the waitpid
system call.
I am then informed whenever the JVM exits, and why it exited, and can take the necessary action.
As pointed out in the other answers, C++ can support finally
-like functionality. The implementation of this functionality that is probably closest to being part of the standard language is the one accompanying the C++ Core Guidelines, a set of best practices for using C++ edited by Bjarne Stoustrup and Herb Sutter. An implementation of finally
is part of the Guidelines Support Library (GSL). Throughout the Guidelines, use of finally
is recommended when dealing with old-style interfaces, and it also has a guideline of its own, titled Use a final_action object to express cleanup if no suitable resource handle is available.
So, not only does C++ support finally
, it is actually recommended to use it in a lot of common use-cases.
An example use of the GSL implementation would look like:
#include <gsl/gsl_util.h>
void example()
{
int handle = get_some_resource();
auto handle_clean = gsl::finally([&handle] { clean_that_resource(handle); });
// Do a lot of stuff, return early and throw exceptions.
// clean_that_resource will always get called.
}
The GSL implementation and usage is very similar to the one in Paolo.Bolzoni's answer. One difference is that the object created by gsl::finally()
lacks the disable()
call. If you need that functionality (say, to return the resource once it's assembled and no exceptions are bound to happen), you might prefer Paolo's implementation. Otherwise, using GSL is as close to using standardized features as you will get.
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
The primary advantage of placing input
inside of label
is typing efficiency for humans and byte storage for computers.
@Znarkus said in his comment to the OP,
One of the big pros of putting the
<input />
inside the<label>
, is that you can omitfor
andid
:<label>My text <input /></label>
in your example. So much nicer!
Note: In @Znarknus code, another efficiency was included not explicitly stated in the comment. type="text"
can also be omitted and input
will render a text box by default.
A side by side comparison of keystrokes and bytes[1].
31 keystrokes, 31 bytes
<label>My Text<input /></label>
58 keystrokes, 58 bytes
<label for="myinput">My Text</label><input id="myinput" />
Otherwise, the snippets are visually equal and they offer the same level of user accessibility. A user can click or tap the label to place the cursor in the text box.
[1] Text files (.txt) created in Notepad on Windows, bytes from Windows File Explorer properties
So if the MySQL Native Driver (mysqlnd) driver is not available, and therefore using bind_result and fetch instead of get_result, the code becomes:
include 'conn.php';
$conn = new Connection();
$query = 'SELECT EmailVerified, Blocked FROM users WHERE Email = ? AND SLA = ? AND `Password` = ?';
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('sss', $_POST['EmailID'], $_POST['SLA'], $_POST['Password']);
$stmt->execute();
$stmt->bind_result($EmailVerified, $Blocked);
while ($stmt->fetch())
{
/* Use $EmailVerified and $Blocked */
}
$stmt->close();
$conn->mysqli->close();
Adding to to @Farhad 's answer based on this answer,
This are the steps to setup a local registry.
Setup in local machine
Setup hostname in local machine: edit /etc/hosts
to add this line
docker.local 127.0.0.1
Now start a local registry (remove -d to run non-daemon mode) :
docker run -d -p 5000:5000 --restart=always --name registry registry:2
Now tag your image properly:
docker tag ubuntu docker.local:5000/ubuntu
Now push your image to local registry:
docker push docker.local:5000/ubuntu
Verify that image is pushed:
curl -X GET http://docker.local:5000/v2/ubuntu/tags/list
Setup in minikube
ssh into minikube with: minukube ssh
edit /etc/hosts
to add this line
docker.local <your host machine's ip>
Verify access:
curl -X GET http://docker.local:5000/v2/ubuntu/tags/list
Now if you try to pull, yo might get an http access error.
Enable insecure access:
If you are always planning to use minkube with this local setup then create a minikube to use insecure registry by default (wont work on existing cluster).
minikube start --insecure-registry="docker.local:5000"
else follow below steps:
systemctl stop docker
edit the docker serice file: get path from systemctl status docker
it might be :
/etc/systemd/system/docker.service.d/10-machine.conf or /usr/lib/systemd/system/docker.service
append this text (replace 192.168.1.4 with your ip)
--insecure-registry docker.local:5000 --insecure-registry 192.168.1.4:5000
to this line
ExecStart=/usr/bin/docker daemon -H tcp://0.0.0.0:2376 -H unix:///var/run/docker.sock --tlsverify --tlscacert /etc/docker/ca.pem --tlscert /etc/docker/server.pem --tlskey /etc/docker/server-key.pem --label provider=virtualbox --insecure-registry 10.0.0.0/24
systemctl daemon-reload
systemctl start docker
try pulling:
docker pull docker.local:5000/ubuntu
Now change your yaml file to use local registry.
containers: - name: ampl-django image: dockerhub/ubuntu
to
containers: - name: ampl-django image: docker.local:5000/nymbleup
Don't use http in production, make the effort for securing things up.
This helped me ..
@Override
public void onBackPressed() {
startActivity(new Intent(currentActivity.this, LastActivity.class));
finish();
}
OR????? even you can use this for drawer toggle also
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
startActivity(new Intent(currentActivity.this, LastActivity.class));
finish();
}
I hope this would help you.. :)
SELECT @variable1 = col1, @variable2 = col2
FROM table1
Read-Host
is a simple option for getting string input from a user.
$name = Read-Host 'What is your username?'
To hide passwords you can use:
$pass = Read-Host 'What is your password?' -AsSecureString
To convert the password to plain text:
[Runtime.InteropServices.Marshal]::PtrToStringAuto(
[Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))
As for the type returned by $host.UI.Prompt()
, if you run the code at the link posted in @Christian's comment, you can find out the return type by piping it to Get-Member
(for example, $results | gm
). The result is a Dictionary where the key is the name of a FieldDescription
object used in the prompt. To access the result for the first prompt in the linked example you would type: $results['String Field']
.
To access information without invoking a method, leave the parentheses off:
PS> $Host.UI.Prompt
MemberType : Method
OverloadDefinitions : {System.Collections.Generic.Dictionary[string,psobject] Pr
ompt(string caption, string message, System.Collections.Ob
jectModel.Collection[System.Management.Automation.Host.Fie
ldDescription] descriptions)}
TypeNameOfValue : System.Management.Automation.PSMethod
Value : System.Collections.Generic.Dictionary[string,psobject] Pro
mpt(string caption, string message, System.Collections.Obj
ectModel.Collection[System.Management.Automation.Host.Fiel
dDescription] descriptions)
Name : Prompt
IsInstance : True
$Host.UI.Prompt.OverloadDefinitions
will give you the definition(s) of the method. Each definition displays as <Return Type> <Method Name>(<Parameters>)
.
Some worthwhile subtleties...
\33[2K
erases the entire line your cursor is currently on
\033[A
moves your cursor up one line, but in the same column i.e. not to the start of the line
\r
brings your cursor to the beginning of the line (r is for carriage return N.B. carriage returns do not include a newline so cursor remains on the same line) but does not erase anything
In xterm specifically, I tried the replies mentioned above and the only way I found to erase the line and start again at the beginning is the sequence (from the comment above posted by @Stephan202 as well as @vlp and @mantal) \33[2K\r
On an implementation note, to get it to work properly for example in a countdown scenario since I wasn't using a new line character '\n'
at the end of each fprintf()
, so I had to fflush()
the stream each time (to give you some context, I started xterm using a fork on a linux machine without redirecting stdout, I was just writing to the buffered FILE pointer fdfile
with a non-blocking file descriptor I had sitting on the pseudo terminal address which in my case was /dev/pts/21
):
fprintf(fdfile, "\33[2K\rT minus %d seconds...", i);
fflush(fdfile);
Note that I used both the \33[2K sequence to erase the line followed by the \r
carriage return sequence to reposition the cursor at the beginning of the line. I had to fflush()
after each fprintf()
because I don't have a new line character at the end '\n'
. The same result without needing fflush() would require the additional sequence to go up a line:
fprintf(fdfile, "\033[A\33[2K\rT minus %d seconds...\n", i);
Note that if you have something on the line immediately above the line you want to write on, it will get over-written with the first fprintf(). You would have to leave an extra line above to allow for the first movement up one line:
i = 3;
fprintf(fdfile, "\nText to keep\n");
fprintf(fdfile, "Text to erase****************************\n");
while(i > 0) { // 3 second countdown
fprintf(fdfile, "\033[A\33[2KT\rT minus %d seconds...\n", i);
i--;
sleep(1);
}
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
The comparison needs to be evaluated fully inside EL ${ ... }
, not outside.
<c:if test="${values.type eq 'object'}">
As to the docs, those ${}
things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.
<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />
By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass()
and then Class#getSimpleName()
instead of adding a custom getter.
<c:forEach items="${list}" var="value">
<c:if test="${value['class'].simpleName eq 'Object'}">
<!-- code here -->
</c:if>
</c:forEeach>
Try dropping the .value
DateTimeExtended(DateTimeExtended myNewDT)
{
this.MyDateTime = myNewDT.MyDateTime;
this.otherdata = myNewDT.otherdata;
}
Clear:both gives you that space between them.
For example your code:
<div style="float:left">Hello</div>
<div style="float:right">Howdy dere pardner</div>
Will currently display as :
Hello ................... Howdy dere pardner
If you add the following to above snippet,
<div style="clear:both"></div>
In between them it will display as:
Hello ................
Howdy dere pardner
giving you that space between hello and Howdy dere pardner.
Js fiiddle http://jsfiddle.net/Qk5vR/1/
Long time ago, but still needed.
info - https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
list - gcc -Q --help=optimizers test.c | grep enabled
disable as many as you like with:
gcc **-fno-web** -Q --help=optimizers test.c | grep enabled
Dictionary<int,string> comboSource = new Dictionary<int,string>();
comboSource.Add(1, "Sunday");
comboSource.Add(2, "Monday");
Aftr adding values to Dictionary
, use this as combobox
datasource:
comboBox1.DataSource = new BindingSource(comboSource, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
For Xamarin Developers, you can use:
intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
If you are working with maven project, then add following dependency to your pom.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
I figured it out, and it's actually pretty straight forward.
Set your variable:
$image1 = "img/products/image1.jpg";
Then ceate a cell, position it, then rather than setting where the image is, use the variable you created above with the following:
$this->Cell( 40, 40, $pdf->Image($image1, $pdf->GetX(), $pdf->GetY(), 33.78), 0, 0, 'L', false );
Now the cell will move up and down with content if other cells around it move.
Hope this helps others in the same boat.
I created a more comprehensive and cleaner version that some people might find useful for remembering which name corresponds to which value. I used Chrome Dev Tool's color code and labels are organized symmetrically to pick up analogies faster:
Note 1: clientLeft
also includes the width of the vertical scroll
bar if the direction of the text is set to right-to-left (since the
bar is displayed to the left in that case)
Note 2: the outermost line represents the closest positioned parent
(an element whose position
property is set to a value different than
static
or initial
). Thus, if the direct container isn’t a positioned
element, then the line doesn’t represent the first container in
the hierarchy but another element higher in the hierarchy. If no
positioned parent is found, the browser will take the html
or body
element as reference
Hope somebody finds it useful, just my 2 cents ;)
Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building RGBA -> JPG + BG
support for sorl thumbnails.
from PIL import Image
png = Image.open(object.logo.path)
png.load() # required for png.split()
background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel
background.save('foo.jpg', 'JPEG', quality=80)
Result @80%
Result @ 50%
I've created a new scheme based on my current app.config to get the messages to disappear. I just used the button in Visual Studio that says "Create Schema" and an xsd schema was created for me.
Save the schema in an apropriate place and see the "Properties" tab of the app.config file where there is a property named Schemas. If you click the change button there you can select to use both the original dotnetconfig schema and your own newly created one.
File.AppendAllText
does not know about the stream you have opened, so will internally try to open the file again. Because your stream is blocking access to the file, File.AppendAllText
will fail, throwing the exception you see.
I suggest you used str.Write
or str.WriteLine
instead, as you already do elsewhere in your code.
Your file is created but contains nothing because the exception is thrown before str.Flush()
and str.Close()
are called.
One of the options is to use the Javascript.
Here is a quick reference where you can start from.
Replace your domain with domainname.com
, it's working with me .
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domainname\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.domainname.com/$1 [R,L]
Use q
flag for quiet mode, and tell wget
to output to stdout with O-
(uppercase o) and redirect to /dev/null
to discard the output:
wget -qO- $url &> /dev/null
>
redirects application output (to a file). if >
is preceded by ampersand, shell redirects all outputs (error and normal) to the file right of >
. If you don't specify ampersand, then only normal output is redirected.
./app &> file # redirect error and standard output to file
./app > file # redirect standard output to file
./app 2> file # redirect error output to file
if file is /dev/null
then all is discarded.
This works as well, and simpler:
wget -O/dev/null -q $url
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
from tkinter import *
def quit(root):
root.close()
root = Tk()
root.title("Quit Window")
def quit(root):
root.close()
button = Button(root, text="Quit", command=quit.pack()
root.mainloop()
An element can take multiple classes:
.classOne { font-weight: bold; }
.classTwo { font-famiy: verdana; }
<div class="classOne classTwo">
<p>I'm bold and verdana.</p>
</div>
And that's about as close as you're going to get unfortunately. I'd love to see this feature, along with class-aliases someday.
"mondate"
is somewhat similar to "Date"
except that adding n
adds n
months rather than n
days:
> library(mondate)
> d <- as.Date("2004-01-31")
> as.mondate(d) + 1
mondate: timeunits="months"
[1] 2004-02-29
Try this definitely work.
SELECT p.PersonID AS person_id,
p.Name, p.SS,
f.FearID AS fear_id,
f.Fear
FROM person_fear AS pf
LEFT JOIN persons AS p ON pf.PersonID = p.PersonID
LEFT JOIN fears AS f ON pf.PersonID = f.FearID
WHERE f.FearID = pf.FearID AND p.PersonID = pf.PersonID
for (int i=0; i<dt_pattern.Rows.Count; i++)
{
DataRow dr = dt_pattern.Rows[i];
}
In the loop, you can now reference row i+1 (assuming there is an i+1)
Add build.gradle
in your project's root directory.
Then just File
-> Invalidate Caches / Restart
Here is a basic build.gradle for Java projects:
plugins {
id 'java'
}
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
version = '1.2.1'
EDIT :
http://codepen.io/gcyrillus/pen/daCyu
So for a popup, you have to use position:fixed , display:table property and max-width with em or rem values :)
with this CSS basis :
#popup {
position:fixed;
width:100%;
height:100%;
display:table;
pointer-events:none;
}
#popup > div {
display:table-cell;
vertical-align:middle;
}
#popup p {
width:80%;
max-width:20em;
margin:auto;
pointer-events:auto;
}
The short answer is no (or should be no). EDIT: yeah, it's possible (see assylias' answer below), but keep reading. EDIT2: but see Stuart Marks' answer for yet another reason why you still shouldn't do it!
The longer answer:
The purpose of these constructs in Java 8 is to introduce some concepts of Functional Programming to the language; in Functional Programming, data structures are not typically modified, instead, new ones are created out of old ones by means of transformations such as map, filter, fold/reduce and many others.
If you must modify the old list, simply collect the mapped items into a fresh list:
final List<Integer> newList = list.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
and then do list.addAll(newList)
— again: if you really must.
(or construct a new list concatenating the old one and the new one, and assign it back to the list
variable—this is a little bit more in the spirit of FP than addAll
)
As to the API: even though the API allows it (again, see assylias' answer) you should try to avoid doing that regardless, at least in general. It's best not to fight the paradigm (FP) and try to learn it rather than fight it (even though Java generally isn't a FP language), and only resort to "dirtier" tactics if absolutely needed.
The really long answer: (i.e. if you include the effort of actually finding and reading an FP intro/book as suggested)
To find out why modifying existing lists is in general a bad idea and leads to less maintainable code—unless you're modifying a local variable and your algorithm is short and/or trivial, which is out of the scope of the question of code maintainability—find a good introduction to Functional Programming (there are hundreds) and start reading. A "preview" explanation would be something like: it's more mathematically sound and easier to reason about to not modify data (in most parts of your program) and leads to higher level and less technical (as well as more human friendly, once your brain transitions away from the old-style imperative thinking) definitions of program logic.
The ==
operator checks to see if the two strings are exactly the same object.
The .equals()
method will check if the two strings have the same value.
Set the PGPASSWORD environment variable inside the script before calling psql
PGPASSWORD=pass1234 psql -U MyUsername myDatabaseName
For reference, see http://www.postgresql.org/docs/current/static/libpq-envars.html
Edit
Since Postgres 9.2 there is also the option to specify a connection string or URI that can contain the username and password.
Using that is a security risk because the password is visible in plain text when looking at the command line of a running process e.g. using ps
(Linux), ProcessExplorer (Windows) or similar tools, by other users.
See also this question on Database Administrators
I just recently started learning XML. The underscore version helps me separate everything XML-related (DOM, XSD, etc.) from programming languages like Java, JavaScript (camel case). And I agree with you that using identifiers which are allowed in programming languages looks better.
Edit: Might be unrelated, but here is a link for rules and recommendations on naming XML elements which I follow when naming ids (sections "XML Naming Rules" and "Best Naming Practices").
You can't use text as a background image, but you can use the :before
or :after
pseudo classes to place a text character where you want it, without having to add all kinds of messy extra mark-up.
Be sure to set position:relative
on your actual text wrapper for the positioning to work.
.mytextwithicon {
position:relative;
}
.mytextwithicon:before {
content: "\25AE"; /* this is your text. You can also use UTF-8 character codes as I do here */
font-family: FontAwesome;
left:-5px;
position:absolute;
top:0;
}
EDIT:
Font Awesome v5 uses other font names than older versions:
font-family: "Font Awesome 5 Free"
font-family: "Font Awesome 5 Pro"
Note that you should set the same font-weight property, too (seems to be 900).
Another way to find the font name is to right click on a sample font awesome icon on your page and get the font name (same way the utf-8 icon code can be found, but note that you can find it out on :before
).
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
Using ensure_ascii=False in json.dumps is the right direction to solve this problem, as pointed out by Martijn. However, this may raise an exception:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 1: ordinal not in range(128)
You need extra settings in either site.py or sitecustomize.py to set your sys.getdefaultencoding() correct. site.py is under lib/python2.7/ and sitecustomize.py is under lib/python2.7/site-packages.
If you want to use site.py, under def setencoding(): change the first if 0: to if 1: so that python will use your operation system's locale.
If you prefer to use sitecustomize.py, which may not exist if you haven't created it. simply put these lines:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
Then you can do some Chinese json output in utf-8 format, such as:
name = {"last_name": u"?"}
json.dumps(name, ensure_ascii=False)
You will get an utf-8 encoded string, rather than \u escaped json string.
To verify your default encoding:
print sys.getdefaultencoding()
You should get "utf-8" or "UTF-8" to verify your site.py or sitecustomize.py settings.
Please note that you could not do sys.setdefaultencoding("utf-8") at interactive python console.
getdate()
or getutcdate()
.
Strive to make your recursive call Tail Recursion (recursion where the last statement is the recursive call). Once you have that, converting it to iteration is generally pretty easy.
GCC works fine. Note that MSVC is not necessarily a valid solution because it does not support C99.
Another method through re
module. It does the reverse operation of matching all the words instead of spitting the whole sentence by space.
>>> import re
>>> s = "many fancy word \nhello \thi"
>>> re.findall(r'\S+', s)
['many', 'fancy', 'word', 'hello', 'hi']
Above regex would match one or more non-space characters.
You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name. Class method overloading is different in PHP than in many other languages. PHP uses the same word but it describes a different pattern.
You can, however, declare a variadic function that takes in a variable number of arguments. You would use func_num_args()
and func_get_arg()
to get the arguments passed, and use them normally.
For example:
function myFunc() {
for ($i = 0; $i < func_num_args(); $i++) {
printf("Argument %d: %s\n", $i, func_get_arg($i));
}
}
/*
Argument 0: a
Argument 1: 2
Argument 2: 3.5
*/
myFunc('a', 2, 3.5);
I know this is an old question, but rather than adding the snapin which is apparently unsupported, I just looked at the EMS shortcut properties and copied those commands.
The full shortcut target is:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"
So I put the following at the start of my script and it seemed to function as expected:
. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
Notes:
v-el:el:uniquename
has been replaced by ref="uniqueName"
. The element is then accessed through this.$refs.uniqueName
.
Import namespace :
using System.Configuration;
Create ConfigurationElement Company :
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get
{
return this["code"] as string;
}
}
}
ConfigurationElementCollection:
public class Companies
: ConfigurationElementCollection
{
public Company this[int index]
{
get
{
return base.BaseGet(index) as Company ;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new Company this[string responseString]
{
get { return (Company) BaseGet(responseString); }
set
{
if(BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((Company)element).Name;
}
}
and ConfigurationSection:
public class RegisterCompaniesConfig
: ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
[ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
public Companies Companies
{
get
{
object o = this["Companies"];
return o as Companies ;
}
}
}
and you must also register your new configuration section in web.config (app.config):
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
then you load your config with
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
A lot of the supplied answers require so many lines per property, ie / and / or - what I'd consider an ugly or tedious implementation because of repetitiveness required for multiple properties, etc. I prefer keeping boiling things down / simplifying them until they can't be simplified anymore or until it doesn't serve much purpose to do so.
In short: in completed works, if I repeat 2 lines of code, I typically convert it into a single line helper function, and so on... I simplify math or odd arguments such as ( start_x, start_y, end_x, end_y ) to ( x, y, w, h ) ie x, y, x + w, y + h ( sometimes requiring min / max or if w / h are negative and the implementation doesn't like it, I'll subtract from x / y and abs w / h. etc.. ).
Overriding the internal getters / setters is an ok way to go, but the problem is you need to do that for every class, or parent the class to that base... This doesn't work for me as I'd prefer to be free to choose the children / parents for inheritance, child nodes, etc.
I have created a solution which answers the question without using a Dict data-type to supply the data as I find that to be tedious to enter the data, etc...
My solution requires you to add 2 extra lines above your class to create a base class for the class you want to add the properties to, then 1 line per and you have the option to add callbacks to control the data, inform you when data changes, restrict the data which can be set based on value and / or data-type, and much more.
You also have the option to use _object.x, _object.x = value, _object.GetX( ), _object.SetX( value ) and they are handled equivalently.
Additionally, the values are the only non-static data which are assigned to the class instance, but the actual property is assigned to the class meaning the things you don't want to repeat, don't need to be repeated... You can assign a default value so the getter doesn't need it each time, although there is an option to override the default default value, and there is another option so the getter returns the raw stored value by overriding default returns ( note: this method means the raw value is only assigned when a value is assigned, otherwise it is None - when the value is Reset, then it assigns None, etc.. )
There are many helper functions too - the first property which gets added adds 2 or so helpers to the class for referencing the instance values... They are ResetAccessors( _key, .. ) varargs repeated ( all can be repeated using the first named args ) and SetAccessors( _key, _value ) with the option of more being added to the main class to aide in efficiency - the ones planned are: a way to group accessors together, so if you tend to reset a few at a time, every time, you can assign them to a group and reset the group instead of repeating the named keys each time, and more.
The instance / raw stored value is stored at class., the __class. references the Accessor Class which holds static vars / values / functions for the property. _class. is the property itself which is called when accessed via the instance class during setting / getting, etc.
The Accessor _class.__ points to the class, but because it is internal it needs to be assigned in the class which is why I opted to use __Name = AccessorFunc( ... ) to assign it, a single line per property with many optional arguments to use ( using keyed varargs because they're easier and more efficient to identify and maintain )...
I also create a lot of functions, as mentioned, some of which use accessor function information so it doesn't need to be called ( as it is a bit inconvenient at the moment - right now you need to use _class..FunctionName( _class_instance, args ) - I got around using the stack / trace to grab the instance reference to grab the value by adding the functions which either run this bit marathon, or by adding the accessors to the object and using self ( named this to point out they're for the instance and to retain access to self, the AccessorFunc class reference, and other information from within the function definitions ).
It isn't quite done, but it is a fantastic foot-hold. Note: If you do not use __Name = AccessorFunc( ... ) to create the properties, you won't have access to the __ key even though I define it within the init function. If you do, then there are no issues.
Also: Note that Name and Key are different... Name is 'formal', used in Function Name Creation, and the key is for data storage and access. ie _class.x where lowercase x is key, the name would be uppercase X so that GetX( ) is the function instead of Getx( ) which looks a little odd. this allows self.x to work and look appropriate, but also allow GetX( ) and look appropriate.
I have an example class set up with key / name identical, and different to show. a lot of helper functions created in order to output the data ( Note: Not all of this is complete ) so you can see what is going on.
The current list of functions using key: x, name: X outputs as:
This is by no means a comprehensive list - there are a few which haven't made it on this at the time of posting...
_instance.SetAccessors( _key, _value [ , _key, _value ] .. ) Instance Class Helper Function: Allows assigning many keys / values on a single line - useful for initial setup, or to minimize lines. In short: Calls this.Set<Name>( _value ) for each _key / _value pairing.
_instance.ResetAccessors( _key [ , _key ] .. ) Instance Class Helper Function: Allows resetting many key stored values to None on a single line. In short: Calls this.Reset<Name>() for each name provided.
Note: Functions below may list self.Get / Set / Name( _args ) - self is meant as the class instance reference in the cases below - coded as this in AccessorFuncBase Class.
this.GetX( _default_override = None, _ignore_defaults = False ) GET: Returns IF ISSET: STORED_VALUE .. IF IGNORE_DEFAULTS: None .. IF PROVIDED: DEFAULT_OVERRIDE ELSE: DEFAULT_VALUE 100
this.GetXRaw( ) RAW: Returns STORED_VALUE 100
this.IsXSet( ) ISSET: Returns ( STORED_VALUE != None ) True
this.GetXToString( ) GETSTR: Returns str( GET ) 100
this.GetXLen( _default_override = None, _ignore_defaults = False ) LEN: Returns len( GET ) 3
this.GetXLenToString( _default_override = None, _ignore_defaults = False ) LENSTR: Returns str( len( GET ) ) 3
this.GetXDefaultValue( ) DEFAULT: Returns DEFAULT_VALUE 1111
this.GetXAccessor( ) ACCESSOR: Returns ACCESSOR_REF ( self.__<key> ) [ AccessorFuncBase ] Key: x : Class ID: 2231452344344 : self ID: 2231448283848 Default: 1111 Allowed Types: {"<class 'int'>": "<class 'type'>", "<class 'float'>": "<class 'type'>"} Allowed Values: None
this.GetXAllowedTypes( ) ALLOWED_TYPES: Returns Allowed Data-Types {"<class 'int'>": "<class 'type'>", "<class 'float'>": "<class 'type'>"}
this.GetXAllowedValues( ) ALLOWED_VALUES: Returns Allowed Values None
this.GetXHelpers( ) HELPERS: Returns Helper Functions String List - ie what you're reading now... THESE ROWS OF TEXT
this.GetXKeyOutput( ) Returns information about this Name / Key ROWS OF TEXT
this.GetXGetterOutput( ) Returns information about this Name / Key ROWS OF TEXT
this.SetX( _value ) SET: STORED_VALUE Setter - ie Redirect to __<Key>.Set N / A
this.ResetX( ) RESET: Resets STORED_VALUE to None N / A
this.HasXGetterPrefix( ) Returns Whether or Not this key has a Getter Prefix... True
this.GetXGetterPrefix( ) Returns Getter Prefix... Get
this.GetXName( ) Returns Accessor Name - Typically Formal / Title-Case X
this.GetXKey( ) Returns Accessor Property Key - Typically Lower-Case x
this.GetXAccessorKey( ) Returns Accessor Key - This is to access internal functions, and static data... __x
this.GetXDataKey( ) Returns Accessor Data-Storage Key - This is the location where the class instance value is stored.. _x
Some of the data being output is:
This is for a brand new class created using the Demo class without any data assigned other than the name ( so it can be output ) which is _foo, the variable name I used...
_foo --- MyClass: ---- id( this.__class__ ): 2231452349064 :::: id( this ): 2231448475016
Key Getter Value | Raw Key Raw / Stored Value | Get Default Value Default Value | Get Allowed Types Allowed Types | Get Allowed Values Allowed Values |
Name: _foo | _Name: _foo | __Name.DefaultValue( ): AccessorFuncDemoClass | __Name.GetAllowedTypes( ) <class 'str'> | __Name.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
x: 1111 | _x: None | __x.DefaultValue( ): 1111 | __x.GetAllowedTypes( ) (<class 'int'>, <class 'float'>) | __x.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
y: 2222 | _y: None | __y.DefaultValue( ): 2222 | __y.GetAllowedTypes( ) (<class 'int'>, <class 'float'>) | __y.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
z: 3333 | _z: None | __z.DefaultValue( ): 3333 | __z.GetAllowedTypes( ) (<class 'int'>, <class 'float'>) | __z.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
Blah: <class 'int'> | _Blah: None | __Blah.DefaultValue( ): <class 'int'> | __Blah.GetAllowedTypes( ) <class 'str'> | __Blah.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
Width: 1 | _Width: None | __Width.DefaultValue( ): 1 | __Width.GetAllowedTypes( ) (<class 'int'>, <class 'bool'>) | __Width.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
Height: 0 | _Height: None | __Height.DefaultValue( ): 0 | __Height.GetAllowedTypes( ) <class 'int'> | __Height.GetAllowedValues( ) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) |
Depth: 2 | _Depth: None | __Depth.DefaultValue( ): 2 | __Depth.GetAllowedTypes( ) Saved Value Restricted to Authorized Values ONLY | __Depth.GetAllowedValues( ) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) |
this.IsNameSet( ): True this.GetName( ): _foo this.GetNameRaw( ): _foo this.GetNameDefaultValue( ): AccessorFuncDemoClass this.GetNameLen( ): 4 this.HasNameGetterPrefix( ): <class 'str'> this.GetNameGetterPrefix( ): None
this.IsXSet( ): False this.GetX( ): 1111 this.GetXRaw( ): None this.GetXDefaultValue( ): 1111 this.GetXLen( ): 4 this.HasXGetterPrefix( ): (<class 'int'>, <class 'float'>) this.GetXGetterPrefix( ): None
this.IsYSet( ): False this.GetY( ): 2222 this.GetYRaw( ): None this.GetYDefaultValue( ): 2222 this.GetYLen( ): 4 this.HasYGetterPrefix( ): (<class 'int'>, <class 'float'>) this.GetYGetterPrefix( ): None
this.IsZSet( ): False this.GetZ( ): 3333 this.GetZRaw( ): None this.GetZDefaultValue( ): 3333 this.GetZLen( ): 4 this.HasZGetterPrefix( ): (<class 'int'>, <class 'float'>) this.GetZGetterPrefix( ): None
this.IsBlahSet( ): False this.GetBlah( ): <class 'int'> this.GetBlahRaw( ): None this.GetBlahDefaultValue( ): <class 'int'> this.GetBlahLen( ): 13 this.HasBlahGetterPrefix( ): <class 'str'> this.GetBlahGetterPrefix( ): None
this.IsWidthSet( ): False this.GetWidth( ): 1 this.GetWidthRaw( ): None this.GetWidthDefaultValue( ): 1 this.GetWidthLen( ): 1 this.HasWidthGetterPrefix( ): (<class 'int'>, <class 'bool'>) this.GetWidthGetterPrefix( ): None
this.IsDepthSet( ): False this.GetDepth( ): 2 this.GetDepthRaw( ): None this.GetDepthDefaultValue( ): 2 this.GetDepthLen( ): 1 this.HasDepthGetterPrefix( ): None this.GetDepthGetterPrefix( ): (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
this.IsHeightSet( ): False this.GetHeight( ): 0 this.GetHeightRaw( ): None this.GetHeightDefaultValue( ): 0 this.GetHeightLen( ): 1 this.HasHeightGetterPrefix( ): <class 'int'> this.GetHeightGetterPrefix( ): (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
And this is after assigning all of _foo properties ( except the name ) the following values in the same order: 'string ', 1.0, True, 9, 10, False
this.IsNameSet( ): True this.GetName( ): _foo this.GetNameRaw( ): _foo this.GetNameDefaultValue( ): AccessorFuncDemoClass this.GetNameLen( ): 4 this.HasNameGetterPrefix( ): <class 'str'> this.GetNameGetterPrefix( ): None
this.IsXSet( ): True this.GetX( ): 10 this.GetXRaw( ): 10 this.GetXDefaultValue( ): 1111 this.GetXLen( ): 2 this.HasXGetterPrefix( ): (<class 'int'>, <class 'float'>) this.GetXGetterPrefix( ): None
this.IsYSet( ): True this.GetY( ): 10 this.GetYRaw( ): 10 this.GetYDefaultValue( ): 2222 this.GetYLen( ): 2 this.HasYGetterPrefix( ): (<class 'int'>, <class 'float'>) this.GetYGetterPrefix( ): None
this.IsZSet( ): True this.GetZ( ): 10 this.GetZRaw( ): 10 this.GetZDefaultValue( ): 3333 this.GetZLen( ): 2 this.HasZGetterPrefix( ): (<class 'int'>, <class 'float'>) this.GetZGetterPrefix( ): None
this.IsBlahSet( ): True this.GetBlah( ): string Blah this.GetBlahRaw( ): string Blah this.GetBlahDefaultValue( ): <class 'int'> this.GetBlahLen( ): 11 this.HasBlahGetterPrefix( ): <class 'str'> this.GetBlahGetterPrefix( ): None
this.IsWidthSet( ): True this.GetWidth( ): False this.GetWidthRaw( ): False this.GetWidthDefaultValue( ): 1 this.GetWidthLen( ): 5 this.HasWidthGetterPrefix( ): (<class 'int'>, <class 'bool'>) this.GetWidthGetterPrefix( ): None
this.IsDepthSet( ): True this.GetDepth( ): 9 this.GetDepthRaw( ): 9 this.GetDepthDefaultValue( ): 2 this.GetDepthLen( ): 1 this.HasDepthGetterPrefix( ): None this.GetDepthGetterPrefix( ): (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
this.IsHeightSet( ): True this.GetHeight( ): 9 this.GetHeightRaw( ): 9 this.GetHeightDefaultValue( ): 0 this.GetHeightLen( ): 1 this.HasHeightGetterPrefix( ): <class 'int'> this.GetHeightGetterPrefix( ): (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
_foo --- MyClass: ---- id( this.__class__ ): 2231452349064 :::: id( this ): 2231448475016
Key Getter Value | Raw Key Raw / Stored Value | Get Default Value Default Value | Get Allowed Types Allowed Types | Get Allowed Values Allowed Values |
Name: _foo | _Name: _foo | __Name.DefaultValue( ): AccessorFuncDemoClass | __Name.GetAllowedTypes( ) <class 'str'> | __Name.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
x: 10 | _x: 10 | __x.DefaultValue( ): 1111 | __x.GetAllowedTypes( ) (<class 'int'>, <class 'float'>) | __x.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
y: 10 | _y: 10 | __y.DefaultValue( ): 2222 | __y.GetAllowedTypes( ) (<class 'int'>, <class 'float'>) | __y.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
z: 10 | _z: 10 | __z.DefaultValue( ): 3333 | __z.GetAllowedTypes( ) (<class 'int'>, <class 'float'>) | __z.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
Blah: string Blah | _Blah: string Blah | __Blah.DefaultValue( ): <class 'int'> | __Blah.GetAllowedTypes( ) <class 'str'> | __Blah.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
Width: False | _Width: False | __Width.DefaultValue( ): 1 | __Width.GetAllowedTypes( ) (<class 'int'>, <class 'bool'>) | __Width.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
Height: 9 | _Height: 9 | __Height.DefaultValue( ): 0 | __Height.GetAllowedTypes( ) <class 'int'> | __Height.GetAllowedValues( ) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) |
Depth: 9 | _Depth: 9 | __Depth.DefaultValue( ): 2 | __Depth.GetAllowedTypes( ) Saved Value Restricted to Authorized Values ONLY | __Depth.GetAllowedValues( ) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) |
Note that because of restricted data-types or value restrictions, some data wasn't assigned - this is by design. The setter prohibits bad data-types or values from being assigned, even from being assigned as a default value ( unless you override the default value protection behavior )
The code hasn't been posted here because I didn't have room after the examples and explanations... Also because it will change.
Please Note: at the time of this posting, the file is messy - this will change. But, if you run it in Sublime Text and compile it, or run it from Python, it will compile and spit out a ton of information - the AccessorDB portion isn't done ( which will be used to update the Print Getters and GetKeyOutput helper functions along with being changed to an Instance function, probably put into a single function and renamed - look for it.. )
Next: Not everything is required for it to run - a lot of the commented stuff at the bottom is for more information used for debugging - it may not be there when you download it. If it is, you should be able to uncomment and recompile to get more information.
I am looking for a work-around to needing MyClassBase: pass, MyClass( MyClassBase ): ... - if you know of a solution - post it.
The only thing necessary in the class are the __ lines - the str is for debugging as is the init - they can be removed from the Demo Class but you will need to comment out or remove some of the lines below ( _foo / 2 / 3 )..
The String, Dict, and Util classes at the top are a part of my Python library - they are not complete. I copied over a few things I needed from the library, and I created a few new ones. The full code will link to the complete library and will include it along with providing updated calls and removing the code ( actually, the only code left will be the Demo Class and the print statements - the AccessorFunc system will be moved to the library )...
Part of file:
##
## MyClass Test AccessorFunc Implementation for Dynamic 1-line Parameters
##
class AccessorFuncDemoClassBase( ):
pass
class AccessorFuncDemoClass( AccessorFuncDemoClassBase ):
__Name = AccessorFuncBase( parent = AccessorFuncDemoClassBase, name = 'Name', default = 'AccessorFuncDemoClass', allowed_types = ( TYPE_STRING ), allowed_values = VALUE_ANY, documentation = 'Name Docs', getter_prefix = 'Get', key = 'Name', allow_erroneous_default = False, options = { } )
__x = AccessorFuncBase( parent = AccessorFuncDemoClassBase, name = 'X', default = 1111, allowed_types = ( TYPE_INTEGER, TYPE_FLOAT ), allowed_values = VALUE_ANY, documentation = 'X Docs', getter_prefix = 'Get', key = 'x', allow_erroneous_default = False, options = { } )
__Height = AccessorFuncBase( parent = AccessorFuncDemoClassBase, name = 'Height', default = 0, allowed_types = TYPE_INTEGER, allowed_values = VALUE_SINGLE_DIGITS, documentation = 'Height Docs', getter_prefix = 'Get', key = 'Height', allow_erroneous_default = False, options = { } )
This beauty makes it incredibly easy to create new classes with dynamically added properties with AccessorFuncs / callbacks / data-type / value enforcement, etc.
For now, the link is at ( This link should reflect changes to the document. ): https://www.dropbox.com/s/6gzi44i7dh58v61/dynamic_properties_accessorfuncs_and_more.py?dl=0
Also: If you don't use Sublime Text, I recommend it over Notepad++, Atom, Visual Code, and others because of proper threading implementations making it much, much faster to use... I am also working on an IDE-like code mapping system for it - take a look at: https://bitbucket.org/Acecool/acecoolcodemappingsystem/src/master/ ( Add Repo in Package Manager first, then Install Plugin - when version 1.0.0 is ready, I'll add it to the main plugin list... )
I hope this solution helps... and, as always:
Just because it works, doesn't make it right - Josh 'Acecool' Moser
When I had the same problem I fixed it by deleting the existing key.snk
in that project and adding a new key.
IF you have tables A
and B
, both with colum C
, here are the records, which are present in table A
but not in B
:
SELECT A.*
FROM A
LEFT JOIN B ON (A.C = B.C)
WHERE B.C IS NULL
To get all the differences with a single query, a full join must be used, like this:
SELECT A.*, B.*
FROM A
FULL JOIN B ON (A.C = B.C)
WHERE A.C IS NULL OR B.C IS NULL
What you need to know in this case is, that when a record can be found in A
, but not in B
, than the columns which come from B
will be NULL, and similarly for those, which are present in B
and not in A
, the columns from A
will be null.
A long-term solution: userscript
You can use a userscript like Tampermonkey (if you are using Chrome or Edge-Chromium, here is the extension)
Then create a script and paste this in it:
// ==UserScript==
// @name Google docs
// @include https://*docs.google.*/document/*
// @grant GM_addStyle
// ==/UserScript==
GM_addStyle ( `
.kix-page-compact::before {
border-top: none;
}
` );
A temporary fix: developer console
You can use the developper console. In Chrome:
1. open your document on google docs
2. click in the url field and press ctrl+shift+I (or right click just above help
and select "view page source)
Then modify the css (cf the steps on the printscreen below) :
1. once the console is loaded press ctrl+F and paste this : kix-page kix-page-compact
2. click on the div just below the one that is highlighted in yellow
3. in the right part, paste this in the filter
box : .kix-page-compact::before
4. click on 1px dotted #aaa
next to border-top
and replace it by none
As already stated, you cannot decrypt MD5 without attempting something like brute force hacking which is extremely resource intensive, not practical, and unethical.
However you could use something like this to encrypt / decrypt passwords/etc safely:
$input = "SmackFactory";
$encrypted = encryptIt( $input );
$decrypted = decryptIt( $encrypted );
echo $encrypted . '<br />' . $decrypted;
function encryptIt( $q ) {
$cryptKey = 'qJB0rGtIn5UB1xG03efyCp';
$qEncoded = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
return( $qEncoded );
}
function decryptIt( $q ) {
$cryptKey = 'qJB0rGtIn5UB1xG03efyCp';
$qDecoded = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "\0");
return( $qDecoded );
}
Using a encypted method with a salt would be even safer, but this would be a good next step past just using a MD5 hash.
The POST data which holds the submitted form data is being echoed in the form, eg:
<input name="firstname" type="text" placeholder="First Name" required="required"
value="<?php echo $_POST['firstname'];?>"
Either clear the POST data once you have done with the form - ie all inputs were ok and you have actioned whatever your result from a form is.
Or, once you have determined the form is ok and have actioned whatever you action from the form, redirect the user to a new page to say "all done, thanks" etc.
header('Location: thanks.php');
exit();
This stops the POST data being present, it's know as "Post/Redirect/Get":
http://en.wikipedia.org/wiki/Post/Redirect/Get
The Post/Redirect/Get (PRG) method and using another page also ensures that if users click browser refresh, or back button having navigated somewhere else, your form is not submitted again.
This means if your form inserts into a database, or emails someone (etc), without the PRG method the values will (likely) be inserted/emailed every time they click refresh or revisit the page using their history/back button.
Add commons-collections4-x.x.jar file in your build path and try it again. It will work.
You can download it from https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.0
Add /usr/local/bin
to your PATH
environment variable, earlier in the list than /usr/bin
.
Generally this is done in your shell's rc file, e.g. for bash, you'd put this in .bashrc
:
export PATH="/usr/local/bin:$PATH"
This will cause your shell to look first for a python
in /usr/local/bin
, before it goes with the one in /usr/bin
.
(Of course, this means you also need to have /usr/local/bin/python
point to python2.7
- if it doesn't already, you'll need to symlink it.)
You can achieve that be using this simple extension method
public static class IEnumerableExtensions
{
public static IEnumerable<t> Randomize<t>(this IEnumerable<t> target)
{
Random r = new Random();
return target.OrderBy(x=>(r.Next()));
}
}
and you can use it by doing the following
// use this on any collection that implements IEnumerable!
// List, Array, HashSet, Collection, etc
List<string> myList = new List<string> { "hello", "random", "world", "foo", "bar", "bat", "baz" };
foreach (string s in myList.Randomize())
{
Console.WriteLine(s);
}
from the docs,
the special thing about methods is that the instance object is passed as the first argument of the function. In our example, the call
x.f()
is exactly equivalent toMyClass.f(x)
. In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s instance object before the first argument.
preceding this the related snippet,
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
x = MyClass()
Add .env file with "SKIP_PREFLIGHT_CHECK=true" than npm start
Assuming that the remote repository has a copy of the develop branch (your initial description describes it in a local repository, but it sounds like it also exists in the remote), you should be able to achieve what I think you want, but the approach is a bit different from what you have envisioned.
Git’s history is based on a DAG of commits. Branches (and “refs” in general) are just transient labels that point to specific commits in the continually growing commit DAG. As such, the relationship between branches can vary over time, but the relationship between commits does not.
---o---1 foo
\
2---3---o bar
\
4
\
5---6 baz
It looks like baz
is based on (an old version of) bar
? But what if we delete bar
?
---o---1 foo
\
2---3
\
4
\
5---6 baz
Now it looks like baz
is based on foo
. But the ancestry of baz
did not change, we just removed a label (and the resulting dangling commit). And what if we add a new label at 4
?
---o---1 foo
\
2---3
\
4 quux
\
5---6 baz
Now it looks like baz
is based on quux
. Still, the ancestry did not change, only the labels changed.
If, however, we were asking “is commit 6
a descendent of commit 3
?” (assuming 3
and 6
are full SHA-1 commit names), then the answer would be “yes”, whether the bar
and quux
labels are present or not.
So, you could ask questions like “is the pushed commit a descendent of the current tip of the develop branch?”, but you can not reliably ask “what is the parent branch of the pushed commit?”.
A mostly reliable question that seems to get close to what you want is:
For all the pushed commit’s ancestors (excluding the current tip of develop and its ancestors), that have the current tip of develop as a parent:
- does at least one such commit exist?
- are all such commits single-parent commits?
Which could be implemented as:
pushedrev=...
basename=develop
if ! baserev="$(git rev-parse --verify refs/heads/"$basename" 2>/dev/null)"; then
echo "'$basename' is missing, call for help!"
exit 1
fi
parents_of_children_of_base="$(
git rev-list --pretty=tformat:%P "$pushedrev" --not "$baserev" |
grep -F "$baserev"
)"
case ",$parents_of_children_of_base" in
,) echo "must descend from tip of '$basename'"
exit 1 ;;
,*\ *) echo "must not merge tip of '$basename' (rebase instead)"
exit 1 ;;
,*) exit 0 ;;
esac
This will cover some of what you want restricted, but maybe not everything.
For reference, here is an extended example history:
A master
\
\ o-----J
\ / \
\ | o---K---L
\ |/
C--------------D develop
\ |\
F---G---H | F'--G'--H'
| |\
| | o---o---o---N
\ \ \ \
\ \ o---o---P
\ \
R---S
The above code could be used to reject H
and S
while accepting H'
, J
, K
, or N
, but it would also accept L
and P
(they involve merges, but they do not merge the tip of develop).
To also reject L
and P
, you can change the question and ask
For all the pushed commit’s ancestors (excluding the current tip of develop and its ancestors):
- are there any commits with two parents?
- if not, does at least one such commit have the current tip of develop its (only) parent?
pushedrev=...
basename=develop
if ! baserev="$(git rev-parse --verify refs/heads/"$basename" 2>/dev/null)"; then
echo "'$basename' is missing, call for help!"
exit 1
fi
parents_of_commits_beyond_base="$(
git rev-list --pretty=tformat:%P "$pushedrev" --not "$baserev" |
grep -v '^commit '
)"
case "$parents_of_commits_beyond_base" in
*\ *) echo "must not push merge commits (rebase instead)"
exit 1 ;;
*"$baserev"*) exit 0 ;;
*) echo "must descend from tip of '$basename'"
exit 1 ;;
esac
Usually a simple hash function works by taking the "component parts" of the input (characters in the case of a string), and multiplying them by the powers of some constant, and adding them together in some integer type. So for example a typical (although not especially good) hash of a string might be:
(first char) + k * (second char) + k^2 * (third char) + ...
Then if a bunch of strings all having the same first char are fed in, then the results will all be the same modulo k, at least until the integer type overflows.
[As an example, Java's string hashCode is eerily similar to this - it does the characters reverse order, with k=31. So you get striking relationships modulo 31 between strings that end the same way, and striking relationships modulo 2^32 between strings that are the same except near the end. This doesn't seriously mess up hashtable behaviour.]
A hashtable works by taking the modulus of the hash over the number of buckets.
It's important in a hashtable not to produce collisions for likely cases, since collisions reduce the efficiency of the hashtable.
Now, suppose someone puts a whole bunch of values into a hashtable that have some relationship between the items, like all having the same first character. This is a fairly predictable usage pattern, I'd say, so we don't want it to produce too many collisions.
It turns out that "because of the nature of maths", if the constant used in the hash, and the number of buckets, are coprime, then collisions are minimised in some common cases. If they are not coprime, then there are some fairly simple relationships between inputs for which collisions are not minimised. All the hashes come out equal modulo the common factor, which means they'll all fall into the 1/n th of the buckets which have that value modulo the common factor. You get n times as many collisions, where n is the common factor. Since n is at least 2, I'd say it's unacceptable for a fairly simple use case to generate at least twice as many collisions as normal. If some user is going to break our distribution into buckets, we want it to be a freak accident, not some simple predictable usage.
Now, hashtable implementations obviously have no control over the items put into them. They can't prevent them being related. So the thing to do is to ensure that the constant and the bucket counts are coprime. That way you aren't relying on the "last" component alone to determine the modulus of the bucket with respect to some small common factor. As far as I know they don't have to be prime to achieve this, just coprime.
But if the hash function and the hashtable are written independently, then the hashtable doesn't know how the hash function works. It might be using a constant with small factors. If you're lucky it might work completely differently and be nonlinear. If the hash is good enough, then any bucket count is just fine. But a paranoid hashtable can't assume a good hash function, so should use a prime number of buckets. Similarly a paranoid hash function should use a largeish prime constant, to reduce the chance that someone uses a number of buckets which happens to have a common factor with the constant.
In practice, I think it's fairly normal to use a power of 2 as the number of buckets. This is convenient and saves having to search around or pre-select a prime number of the right magnitude. So you rely on the hash function not to use even multipliers, which is generally a safe assumption. But you can still get occasional bad hashing behaviours based on hash functions like the one above, and prime bucket count could help further.
Putting about the principle that "everything has to be prime" is as far as I know a sufficient but not a necessary condition for good distribution over hashtables. It allows everybody to interoperate without needing to assume that the others have followed the same rule.
[Edit: there's another, more specialized reason to use a prime number of buckets, which is if you handle collisions with linear probing. Then you calculate a stride from the hashcode, and if that stride comes out to be a factor of the bucket count then you can only do (bucket_count / stride) probes before you're back where you started. The case you most want to avoid is stride = 0, of course, which must be special-cased, but to avoid also special-casing bucket_count / stride equal to a small integer, you can just make the bucket_count prime and not care what the stride is provided it isn't 0.]
You were very close with your original example. You could either use @jAndy's suggestion or:
if (typeof FB != 'undefined')
/****************************************/
/* version 1 */
/****************************************/
var Animal = function(params) {
this.say = function()
{
console.log(params);
}
};
var Cat = function() {
Animal.call(this, "moes");
};
var Dog = function() {
Animal.call(this, "vewa");
};
var cat = new Cat();
var dog = new Dog();
cat.say();
dog.say();
/****************************************/
/* version 2 */
/****************************************/
var Cat = function(params) {
this.say = function()
{
console.log(params);
}
};
var Dog = function(params) {
this.say = function()
{
console.log(params);
}
};
var Animal = function(type) {
var obj;
var factory = function()
{
switch(type)
{
case "cat":
obj = new Cat("bark");
break;
case "dog":
obj = new Dog("meow");
break;
}
}
var init = function()
{
factory();
return obj;
}
return init();
};
var cat = new Animal('cat');
var dog = new Animal('dog');
cat.say();
dog.say();
This error shows up when you are treating an array or string as a Hash. In this line myHash.each do |item|
you are assigning item
to a two-element array [key, value]
, so item[:symbol]
throws an error.
Use this stylesheet:
/* Sticky footer styles_x000D_
-------------------------------------------------- */_x000D_
html {_x000D_
position: relative;_x000D_
min-height: 100%;_x000D_
}_x000D_
body {_x000D_
/* Margin bottom by footer height */_x000D_
margin-bottom: 60px;_x000D_
}_x000D_
.footer {_x000D_
position: absolute;_x000D_
bottom: 0;_x000D_
width: 100%;_x000D_
/* Set the fixed height of the footer here */_x000D_
height: 60px;_x000D_
line-height: 60px; /* Vertically center the text there */_x000D_
background-color: #f5f5f5;_x000D_
}_x000D_
_x000D_
_x000D_
/* Custom page CSS_x000D_
-------------------------------------------------- */_x000D_
/* Not required for template or sticky footer method. */_x000D_
_x000D_
body > .container {_x000D_
padding: 60px 15px 0;_x000D_
}_x000D_
_x000D_
.footer > .container {_x000D_
padding-right: 15px;_x000D_
padding-left: 15px;_x000D_
}_x000D_
_x000D_
code {_x000D_
font-size: 80%;_x000D_
}
_x000D_
When we use multiple and
(where) condition with last (where + or where) the where condition fails most of the time. for that we can use the nested where function with parameters passing in that.
$feedsql = DB::table('feeds as t1')
->leftjoin('groups as t2', 't1.groups_id', '=', 't2.id')
->where('t2.status', 1)
->whereRaw("t1.published_on <= NOW()")
>whereIn('t1.groupid', $group_ids)
->where(function($q)use ($userid) {
$q->where('t2.contact_users_id', $userid)
->orWhere('t1.users_id', $userid);
})
->orderBy('t1.published_on', 'desc')->get();
The above query validate all where condition then finally checks where t2.status=1 and (where t2.contact_users_id='$userid' or where t1.users_id='$userid')
Back in the old days of Python, to call a function with arbitrary arguments, you would use apply
:
apply(f,args,kwargs)
apply
still exists in Python2.7 though not in Python3, and is generally not used anymore. Nowadays,
f(*args,**kwargs)
is preferred. The multiprocessing.Pool
modules tries to provide a similar interface.
Pool.apply
is like Python apply
, except that the function call is performed in a separate process. Pool.apply
blocks until the function is completed.
Pool.apply_async
is also like Python's built-in apply
, except that the call returns immediately instead of waiting for the result. An AsyncResult
object is returned. You call its get()
method to retrieve the result of the function call. The get()
method blocks until the function is completed. Thus, pool.apply(func, args, kwargs)
is equivalent to pool.apply_async(func, args, kwargs).get()
.
In contrast to Pool.apply
, the Pool.apply_async
method also has a callback which, if supplied, is called when the function is complete. This can be used instead of calling get()
.
For example:
import multiprocessing as mp
import time
def foo_pool(x):
time.sleep(2)
return x*x
result_list = []
def log_result(result):
# This is called whenever foo_pool(i) returns a result.
# result_list is modified only by the main process, not the pool workers.
result_list.append(result)
def apply_async_with_callback():
pool = mp.Pool()
for i in range(10):
pool.apply_async(foo_pool, args = (i, ), callback = log_result)
pool.close()
pool.join()
print(result_list)
if __name__ == '__main__':
apply_async_with_callback()
may yield a result such as
[1, 0, 4, 9, 25, 16, 49, 36, 81, 64]
Notice, unlike pool.map
, the order of the results may not correspond to the order in which the pool.apply_async
calls were made.
So, if you need to run a function in a separate process, but want the current process to block until that function returns, use Pool.apply
. Like Pool.apply
, Pool.map
blocks until the complete result is returned.
If you want the Pool of worker processes to perform many function calls asynchronously, use Pool.apply_async
. The order of the results is not guaranteed to be the same as the order of the calls to Pool.apply_async
.
Notice also that you could call a number of different functions with Pool.apply_async
(not all calls need to use the same function).
In contrast, Pool.map
applies the same function to many arguments.
However, unlike Pool.apply_async
, the results are returned in an order corresponding to the order of the arguments.
Why don't you instead use a one-line HTTP server?
python -m SimpleHTTPServer 8000
will serve the contents of the current working directory over HTTP on port 8000.
If you use Python 3, you should instead write
python3 -m http.server 8000
See the SimpleHTTPServer module docs for 2.x and the http.server docs for 3.x.
By the way, in both cases the port parameter is optional.
Make sure you have qmake in your path (which qmake), and that it works (qmake -v) (IF you have to kill it with ctr-c then there is something wrong with your environment).
Then follow this: http://developer.qt.nokia.com/doc/qt-4.8/gettingstartedqt.html
Here is how to get the code for an embedded image without worrying about any files or base64 statements or mimes (it's still base64, but you don't have to do anything to get it). I originally posted this same answer in this thread, but it may be valuable to repeat it in this one, too.
To do this, you need Mozilla Thunderbird, you can fetch the html code for an image like this:
You should end up with a string of text something like this:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAaIAAAGcCAIAAAAUGTPlAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAPbklEQVR4nO3d2ZbixhJAUeku//8vcx/oxphBaMgpIvd+c7uqmqakQ6QkxHq73RaA3tZ13fNlJ5K1yhzQy860fbS/XTIHtHOla9/8jJjMARXV6No332omc0BhLdP27r1pMgeU0bduz16yJnPAVeME7uG5bDIHxTzv7bn3rAG79u7xK/in7+OArNY14QwRom7v/tf7AUASQROw07qu4f6Bjwcsc1BLuC58FDFwD/dHbtEKtWwvWl/aMeAKN27dXpjmoIyLnRqtKaM9ntPWdTXNQRWHRrmhjPzYzjHNQXnnJrsR+jLCYyjONAej6Ht4LmXg7kxzUMahTAx1wiH0udQ9ZA6G0Ct8uQN3Z9EKBeyPxThvCJshcHcJ348CFx29ou1jLz7cDmikC+Xmadxi0Qo/XS/C+8EvjWvJohX+42gCtr9+56DX0myNW0xzsMeJNHw7falx7Znm4Lyj1ThxmK9gFuds3GKagxdfPzblr+c/afWgCoj1aMtyphVevZ8uKNKIc2ds93zjTzM3brFohXc1Xvs7zhOTN24xzcFOvWKR7P5OXTg2ByRnmoO9ak9GxXdGo9yyLLfbzTQHQ9C4ekxzcECNdtTYBzXu7v7cmubggOJJMmc0IHPQTaXGGeXuHk+v6+agg3pDnMa9M83BAW3eDsF1z0+yzMFe4zfOKPeRzEFT9UqkcQ8vryUyB7sUjEiNHmncBqcg4LfiEbn/wPd7nzhsd937c2iagx9aLjPP/V1GuW2mOdhSqiCPEaPSYMjdx3FY5uCr6wV53+ue/+Tjz19Xb8EsTObgsyuNu9KpQ99rlHv27amTOfjgXD6O1q3U7dfZJnPwqvjndVX6URL5bOOpkzn4j0PtuB44h+GK2H4aXVACf3z7AOlvNj7qsNAj2mKU2880B8tybaG6ffmbea22358M6XcAZRv381uuM8o97HliTXNpeRfRTlcWqvu/t8jVcOp2jszNwkWnH51uXMviqNs3OzdpmcvJjrHH4G8g9UssReYmYqB7diIiTqEOZf/GLHNhXD/WpnEPA6ZkwIc0skMbs+vmYjh6xx5F2zBUUNa/ej+QSI5u3qa5WQjf3ThBGeeRpCdzgW0fa7v/r8ddats9rIGNUJYRHkNoJzZmmQtMvA7p3pfuDyCBc9u8zGVmv7rzPORw+nXdKYgYTvyC7dt3ngdMc2FcuQR/5xVzyd4fJnCZXNkaTXOBbezGRa59DZ2J0A+eFxdfcWUuNjvzR56WTK6vKmQuocl38sn/+ckUOXIic+HZq595NjIpdXRY5kLauOvZuaNyH78r3CkIjcuk4ObnTOu83qMQrmtkVXZTNM0lcW/WnnOvWd8rnu9fNK3iL7emuTx+7uduasL4amyHpjmWReMYQ6XtUObQOJKTudlpHIOotyk6NjeiZO8thW21t3CZG87H95ZW2g72/1jlpZIG25JFa1TXN47Tjfv4J3BCm9dLmYuheFaMY/R1u92abYQyF4MqkUnj7VnmZpQymin/Ufm0HOIeZG44tTeCIp9jPWBTHC4cXJfA3dU6hUcpz3vvxo1Jdkr56xa4wXXf6mQugG+lO7p7p/ld61ogI2x1rpsLpt41dCGujBO4EEbbeGQuntOl21j/FvxbKhG42h6/7tNP9VAbzLOxNmW++XYLzCI7/+12G/PuwdLWTPffdVUyF0OvHb7bqTGBa2WGArighK80Lr0ZGrfIXBT1NsfbX5V+/lEa18w4v/TanIKY1M9NvP0+IHAtzdO4xbG5cC62YMxft8C1NOY2UJVpbgrDbtkC19iwW0JVjs3lN+yWrXGNDbsl1GaaowOBa2/axi0yl96hjbvBRcIC197MgbuzaGVZlmVd128BKhgmjWtP4xbTXG7bm/j+6Ny/8soOI3BdaNydzM2oZXQErguBe+a6uUgOJePjb7bxZXca14Wd+oVjc7PYOPp26IdU+mJK0bh3MpfT9dupX6RxXWjcR47NZdalNQLXhcBtkLmEvt0ms4jtuwprXBfNGhfiTvrvZC6Mo9d/NCZwvexszaFb5P/8CbE4NkcBcXeA6E407v0/T4vyezfNxTDy9jTyY0ts/0TmF2Sa4xK7UBfXD4qV+rCk6z+kAZnjpCIX4nHO9Wf+RKGiRO2dd0EEoCZs2LMLf/sAzP0ePyFiMUxzENueV8GXNk3VuEXmxmeU46eql0lGb9ziTCvwUabXV9Mc5Hf0urnrx/KGYpobWqZXVEJocKP89kxzEN6JDH3MWdaXVdPcuLJuczS2Z0Pa+Jroo9wiczC57QgmaNwic8MyylHExoY0zzbm2BzEVm/gyjHKLaa5Mc3zMstFVUuU4MLgO5mDqH7Wp/h95d7/xut362zAW/eHY5RjfPduRLmK2DQHHBbrxdgpiLHE2nrgxZgbsGkOKPY+ijEXraa5gYz5SsgMTmx7YxbtI5kDluXUXe8v3q2zGWdaR2GUYxzJsmCaA14le9E1zQ0h2VZFGjn6YJoDvsrxAixzwJYEH8jrujngt3Vd39/gFWVJ69jcEKK/WhLIx13+9BYYIiAy15/G0dLpz6Iu9QPbs2iFuTyWnzs9f3HQl2SnIGA6QWt1msxBErfbrfb68f3nj79iXWQOcnjkZmfsigx0IRq3OAUxgtlWEJS1vQvP8PmEPzkFAVHtidTja2Z+NTXN9Tfz9sc5p3fbOYc7metP5tiv1A77batLGQSZG4LSsa3GfhroLucXOdMKQ2twmcizlK+4TkEM4Xa7pdy8OK3XVGWao6KUmxcnNBvf5tnkHJsbi5kuqCvzeN99MOKNlY6SuXFJXiDv92Lb+S00IHMxSN7I7ESDk7nY5K87e9D4nIIITOO607gQZC4qjYOdXDcXksZ1Z44LxDQXj8Z1p3GxyBwco3HhyFwwRrm+NC4imYO9NC4omYNdNC4umYvEirUXjQtN5sLQuF40LjrXzcFXApeDaS4Go1x7GpeGzMEHGpeJRSv8h8DlI3Pwh8BlJXMBODBXm8Dl5tgcs9O49GRudEa5qjRuBhatTErg5iFzTEfgZiNzQ7NiLUvg5iRzTEHgZiZzJCdwONM6LivW6zSOxTRHVgLHg2mOhDSOZ6a5QVmxnqBufCRzZCBwbLBoJTyNY9tqExmQFes5NmY+Ms2Rx7quXiF4J3Nko3S8kDkSUjqeydxw7KJFeBp5kDkgOZkjLQMddzIHJCdzYzGAQHEyByQnc0ByMkda3vvFncwNxIE5qEHmgORkjpysWHmQOSA5mSMhoxzPZA5ITubIxijHC5kjFY3jncwBycncKFwbfJ1Rjo9kjiQ0jm9kjgw0jg0yByT3T+8HAFf9HOVejnsa/WZjmhuC8w+nHW0cE5I5Ajs3lwnfbGSOqKw92UnmCOlK4/RxNk5BkNztdju3Sn3+LmUMzTRHPKejc7vddn7vSxkdzgtN5vqzCx1isOIomSOSE40r9Sri1SgumSOMjo0797czCJkjhsaNE7VMnGklgJaN+/iNqheazDG6Nol5r5u0pSFzjK7qsf9vP1zjMpE5ZrSdTo1LRuaYyJ7BUOPycaYV/qVxKckc/KFxWckcLIvGpSZzoHHJyRws67p6y2pizrTCH4/SvQx3PjEnOtMcvFr/+vZ/Gz8eLjLNwVeKloPM8cd9LTbVjr1n+fnxCVnX1dI1EItWluVph7f37uFZikXmOhtweppnH/ber0lYtPJhTz79aVilbJ/r7Ev4wnGIobPuO/DGBtDmsbn1ObXJXGcjZ+6h7IMsvsldfHh2gfQsWqe2cw+/eBK2dkcmPEfMIaa5zoY6BBbdxpO5ncJkzwMvTHPk8XOs+/YFz38iefm4oIRsPp44fvnP7ideaEnm5pV4bNnzT9uOHZnIHPkdHdAMdMnIXE92p2YOPdWmvGRkblK59+T9Ucv9PHAnc8xiZ/uELx8XlDCLb/3StfRMcySkXDyTuRlNWIEJ/8k8WLSSk67xYJoDkpO56RhzmI3MAcnJ3FyMckxI5oDkZG4iRjnmJHNAcjIHJCdzQHIyByQnc7Nw/oFpyRyQnMwByclcNz4IAtqQuSk4MMfMZA5ITuaA5GQuPytWJidzQHIyByQnc8lZsYLMAcnJHJCczGVmxQqLzPXinV7QjMylZZSDO5kDkpO5nIxy8CBzQHIyByQnc0ByMgckJ3MJOf8Az2SuA9cGQ0syByQnc9lYscILmQOSkzkgOZkDkpO51qqeZnVgDt7JHJCczAHJyVweVqzwkcwByclcU/XOPxjl4BuZA5KTOSA5mcvAihU2yByQnMy1U+n8g1EOtskckJzMAcnJXGxWrPCTzAHJyVwjNc4/GOVgD5kDkpM5IDmZi8qKFXaSOSA5mQvJKAf7yVwLVT/mBtgmc0ByMhePFSscInNAcjIXjFEOjpK56px/gL5kDkhO5uoqO8pZscIJMgckJ3NhGOXgHJmryMkHGIHMAcnJXAxWrHCazNVixQqDkLkAjHJwhcwByclcFQVXrEY5uEjmgORkbmhGObhO5oDkZG5cRjkoQubKc8UcDEXmBmWUg1JkrjCjHIxG5kZklIOCZA5ITuZKsmKFAclcMaUaZ8UKZcncWDQOipO5MixXYVgyNxCjHNQgcwUY5WBkMjcKoxxUInNXFRnlNA7qkTkgOZnrzygHVcncJU4+wPhk7jxH5SAEmQOSk7mTjHIQhcwBycncGc48QCAy140VK7Qhc4c5KgexyFwHGgctydwx10c5jYPGZA5ITuYOMMpBRDK3l8ZBUDK3i8ZBXDIHJCdzvxnlIDSZ+0HjIDqZ2+K9q5CAzH3lTV2Qg8wBycncZ0Y5SEPmPtA4yETmXmkcJCNz5WkcDEXm/sNVcpCPzP1L4yAlmftD4yArmVsWjYPUZM47uiC52TPn8hFIb+rMaRzMYN7MaRxMYtLMaRzMY8bMaRxMZbrMaRzMZq7MaRxM6J/eD6CRUhfHaRyEM8U0p3Ews/yZ0ziYXOZFa8F3cWkcxJV2mtM44C7nNGehCjxky5whDniRJ3Nl76ekcZBGhswJHLAhduaK3xFT4yCfwGdaNQ7YI+Q0J3DAfsEyV+NzGzQOcguTuUofTKNxkF6AzAkccMW4mav3uYICB1MZMXNVPzhV42A2Y2VO4IDiRsmcwAGV9Mxc1bTdCRzQJ3MCBzTTOnO1A6duwIsWmWswuy0CB3xRJXNtuvYgcMCGYplrnLY7gQN+upq5LnVbBA7Y7VjmekXtmcABh+zKXPe6SRtw2mvmuhftQdqAIv5kbpC6SRtQXP+6SRtQ1XqvjCvdgKzW9+L42FMgk/8DDsgw4HlIEQ0AAAAASUVORK5CYII=" alt="" height="211" width="213">
You can wrap this up into a string variable and place this absolutely anywhere that you would present an html email message - even in your email signatures. The advantage is that there are no attachments, and there are no links. (this code will display a lizard)
A picture is worth a thousand words:
Incidentally, I did write a program to do all of this for you. It's called BaseImage, and it will create the image code as well as the html for you. Please don't consider this self-promotion; I'm just sharing a solution.
The best answer I got
<style name="MyRatingBar" parent="@android:style/Widget.RatingBar">
<item name="android:minHeight">15dp</item>
<item name="android:maxHeight">15dp</item>
<item name="colorControlNormal">@color/white</item>
<item name="colorControlActivated">@color/home_add</item>
</style>
user like this
<RatingBar
style="?android:attr/ratingBarStyleIndicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:isIndicator="false"
android:max="5"
android:rating="3"
android:scaleX=".8"
android:scaleY=".8"
android:theme="@style/MyRatingBar" />
Increase/Decrease sizes by using scaleX and scaleY value
Try below code,
UIView *view1 = [[UIView alloc]init];
view1.backgroundColor = [UIColor blackColor];
[view1 setFrame:CGRectMake(0, 0, 50, 50)];
UIView *view2 = [[UIView alloc]init];
view2.backgroundColor = [UIColor greenColor];
[view2 setFrame:CGRectMake(0, 100, 100, 100)];
NSArray *subView = [NSArray arrayWithObjects:view1,view2, nil];
[self.stack1 initWithArrangedSubviews:subView];
Hope it works. Please let me know if you need anymore clarification.
It's the same. Your international format is already correct, and is recommended for use in all cases, where possible.
Please try this:
$uri = $_SERVER['REQUEST_URI']; // $uri == example.com/sub
$exploded_uri = explode('/', $uri); //$exploded_uri == array('example.com','sub')
$domain_name = $exploded_uri[1]; //$domain_name = 'example.com'
I hope this will help you.
GRANT SELECT ON *.* TO 'user'@'localhost' IDENTIFIED BY 'password';
This will create a user with SELECT
privilege for all database including Views.
Use get_browser()
function.
It can give you output like this:
Array
(
[browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
[browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
[parent] => Firefox 0.9
[platform] => WinXP
[browser] => Firefox
[version] => 0.9
[majorver] => 0
[minorver] => 9
....
It is a bad idea to select * from anything, period. This is why SSMS adds every field name, even if there are hundreds, instead of select *. It is extremely inefficient regardless of how large the table is. If you don't know what the fields are, its still more efficient to pull them out of the INFORMATION_SCHEMA database than it is to select *.
A better query would be:
SELECT
COLUMN_NAME,
Case
When DATA_TYPE In ('varchar', 'char', 'nchar', 'nvarchar', 'binary')
Then convert(varchar(MAX), CHARACTER_MAXIMUM_LENGTH)
When DATA_TYPE In ('numeric', 'int', 'smallint', 'bigint', 'tinyint')
Then convert(varchar(MAX), NUMERIC_PRECISION)
When DATA_TYPE = 'bit'
Then convert(varchar(MAX), 1)
When DATA_TYPE IN ('decimal', 'float')
Then convert(varchar(MAX), Concat(Concat(NUMERIC_PRECISION, ', '), NUMERIC_SCALE))
When DATA_TYPE IN ('date', 'datetime', 'smalldatetime', 'time', 'timestamp')
Then ''
End As DATALEN,
DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
Where
TABLE_NAME = ''
Well the easiest way that I do it is by typing the following into the .m file.
- (BOOL) prefersStatusBarHidden
{
return YES;
}
This should work!
Pure JavaScript:
var button = document.getElementById('button'); // Assumes element with id='button'
button.onclick = function() {
var div = document.getElementById('newpost');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
};
jQuery:
$("#button").click(function() {
// assumes element with id='button'
$("#newpost").toggle();
});
1.Click on Configure
2.Then Choose Project Defaults
3.Click on Project Structure
4.Set android sdk path
You will find here "C:\User\YourPcname\AppData\Local\SDK"
Note: Sometime AppData
may hidden if it will not show then enable show hidden content.
5.Apply Changes
6.Then Select Sdk From Configure
option
7.Then Android sdk manager page is open
8.In bottom you will see Install packages
option
9.Install them and enjoy.
To avoid blank line skipping (give readability in conf file) I combine aflat and jeb answer (here) to something like this:
@echo off
setlocal enabledelayedexpansion
set INTEXTFILE=test.txt
set OUTTEXTFILE=test_out.txt
set SEARCHTEXT=bath
set REPLACETEXT=hello
set OUTPUTLINE=
for /f "tokens=1,* delims=¶" %%A in ( '"findstr /n ^^ %INTEXTFILE%"') do (
SET string=%%A
for /f "delims=: tokens=1,*" %%a in ("!string!") do set "string=%%b"
if "!string!" == "" (
echo.>>%OUTTEXTFILE%
) else (
SET modified=!string:%SEARCHTEXT%=%REPLACETEXT%!
echo !modified! >> %OUTTEXTFILE%
)
)
del %INTEXTFILE%
rename %OUTTEXTFILE% %INTEXTFILE%
The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?
For example, we have i values and get the value of id field
alert(obj[i].id); //works!
But what if we need key with spaces?
In this case, the following construction can help (without point between [] blocks):
alert(obj[i]["No. of interfaces"]); //works too!
You can pass your arguments using this encodeURIComponent function so you don't have to worry about passing any special characters.
data: "param1=getAccNos¶m2="+encodeURIComponent('Dolce & Gabbana')
OR
var someValue = 'Dolce & Gabbana';
data: "param1=getAccNos¶m2="+encodeURIComponent(someValue)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
This one is ugly, but just want to throw there some other options to the mix. This one has no loops. I use it for debugging purposes
var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}
var myStrObj = JSON.stringify(myObject)
var myHtmlTableObj = myStrObj.replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")
$('#myDiv').html(myHtmlTableObj)
Example:
var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}_x000D_
var myStrObj = JSON.stringify(myObject)_x000D_
var myHtmlTableObj = myStrObj.replace(/\"/g,"").replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")_x000D_
_x000D_
$('#myDiv').html(myHtmlTableObj)
_x000D_
#myDiv table td{background:whitesmoke;border:1px solid lightgray}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div id='myDiv'>table goes here</div>
_x000D_
Try string manipulation:
var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var newTxt = txt.split('(');
for (var i = 1; i < newTxt.length; i++) {
console.log(newTxt[i].split(')')[0]);
}
or regex (which is somewhat slow compare to the above)
var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var regExp = /\(([^)]+)\)/g;
var matches = txt.match(regExp);
for (var i = 0; i < matches.length; i++) {
var str = matches[i];
console.log(str.substring(1, str.length - 1));
}
It depends on the database you are using. MySQL for example supports the (non-standard) group_concat function. So you could write:
SELECT GROUP_CONCAT(ModuleValue) FROM Table_X WHERE ModuleID=@ModuleID
Group-concat is not available at all database servers though.
SO what I change is I load upload library each time
$config = array();
$config['upload_path'] = $filePath;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
$files = $_FILES;
$count = count($_FILES['nameUpload']['name']);
for($i=0; $i<$count; $i++)
{
$this->load->library('upload', $config);
$_FILES['nameUpload']['name']= $files['nameUpload']['name'][$i];
$_FILES['nameUpload']['type']= $files['nameUpload']['type'][$i];
$_FILES['nameUpload']['tmp_name']= $files['nameUpload']['tmp_name'][$i];
$_FILES['nameUpload']['error']= $files['nameUpload']['error'][$i];
$_FILES['nameUpload']['size']= $files['nameUpload']['size'][$i];
$this->upload->do_upload('nameUpload');
}
And it work for me.
Use javascript:
<button onclick="window.location.href='/css_page.html'">CSS page</button>
You can always style the button in css anyaways. Hope it helped!
Good luck!
s/\([^)]*\)//
So in Python, you'd do:
re.sub(r'\([^)]*\)', '', filename)
You can write following codes to achieve this task:
SELECT ... FROM ... WHERE ...
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'
It export the result to CSV and then export it to excel sheet.
If you are on Linux/Unix have a look at mbstowcs() and wcstombs() defined in GNU C (from ISO C 90).
mbs stand for "Multi Bytes String" and is basically the usual zero terminated C string.
wcs stand for Wide Char String and is an array of wchar_t.
For more background details on wide chars have a look at glibc documentation here.
You can use Underscore String Library as following
var common="#box"
var href="#box1"
_(href).strRight(common)
result will be : 1
See :https://github.com/epeli/underscore.string
DEMO:
http://jsfiddle.net/abdennour/Vyqtt/
HTML Code :
<p>
<a href="#box1" >img1</a>
<a href="#box2" >img2</a>
<a href="#box3" >img3</a>
<a href="#box4" >img4</a>
</p>
<div style="font-size:30px"></div>
JS Code :
var comm="#box"
$('a').click(function(){
$('div').html(_($(this).attr('href')).strRight(comm))})
if you have suffix as following :
href="box1az"
You can use the next demo :
http://jsfiddle.net/abdennour/Vyqtt/1/
function retrieveNumber(all,prefix,suffix){
var left=_(all).strRight(prefix);
return _(left).strLeft(suffix);
}
Sounds like you got your answer. Passing by value is expensive, but gives you a copy to work with if you need it.
"whats my ip"
or entering this command: wget http://ipinfo.io/ip -qO -
wget http://ipinfo.io/ip -qO -
again from there too.6006
123.123.12.32:6006
If your remote server is open to traffic from your local IP address, you should be able to see your remote Tensorboard.
Warning: if all internet traffic can access your system (if you haven't specified a single IP address that can access it), anyone may be able to view your TensorBoard results and runaway with creating SkyNet themselves.
Just to complete it:
(gdb) p (char[10]) *($ebx)
$87 = "asdfasdfe\n"
You must give a length, but may change the representation of that string:
(gdb) p/x (char[10]) *($ebx)
$90 = {0x61,
0x73,
0x64,
0x66,
0x61,
0x73,
0x64,
0x66,
0x65,
0xa}
This may be useful if you want to debug by their values
$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);
On OSX, the command will depend on the flavour of python installation you have.
Python 2.x - Default
sudo pip install requests
Python 3.x
sudo pip3 install requests
import ctypes
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)
The last number (here 1) can be change to change window style (not only buttons!):
## Button styles:
# 0 : OK
# 1 : OK | Cancel
# 2 : Abort | Retry | Ignore
# 3 : Yes | No | Cancel
# 4 : Yes | No
# 5 : Retry | No
# 6 : Cancel | Try Again | Continue
## To also change icon, add these values to previous number
# 16 Stop-sign icon
# 32 Question-mark icon
# 48 Exclamation-point icon
# 64 Information-sign icon consisting of an 'i' in a circle
For example,
ctypes.windll.user32.MessageBoxW(0, "That's an error", "Warning!", 16)
will give this:
A little anecdote to illustrate the use of array_key_exists
.
// A programmer walked through the parking lot in search of his car
// When he neared it, he reached for his pocket to grab his array of keys
$keyChain = array(
'office-door' => unlockOffice(),
'home-key' => unlockSmallApartment(),
'wifes-mercedes' => unusedKeyAfterDivorce(),
'safety-deposit-box' => uselessKeyForEmptyBox(),
'rusto-old-car' => unlockOldBarrel(),
);
// He tried and tried but couldn't find the right key for his car
// And so he wondered if he had the right key with him.
// To determine this he used array_key_exists
if (array_key_exists('rusty-old-car', $keyChain)) {
print('Its on the chain.');
}
I would like to add some more things on top of Bert F answer.
Locks
support various methods for finer grained lock control, which are more expressive than implicit monitors (synchronized
locks)
A Lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, such as the read lock of a ReadWriteLock.
Advantages of Lock over Synchronization from documentation page
The use of synchronized methods or statements provides access to the implicit monitor lock associated with every object, but forces all lock acquisition and release to occur in a block-structured way
Lock implementations provide additional functionality over the use of synchronized methods and statements by providing a non-blocking attempt to acquire a lock (tryLock())
, an attempt to acquire the lock that can be interrupted (lockInterruptibly()
, and an attempt to acquire the lock that can timeout (tryLock(long, TimeUnit))
.
A Lock class can also provide behavior and semantics that is quite different from that of the implicit monitor lock, such as guaranteed ordering, non-reentrant usage, or deadlock detection
ReentrantLock: In simple terms as per my understanding, ReentrantLock
allows an object to re-enter from one critical section to other critical section . Since you already have lock to enter one critical section, you can other critical section on same object by using current lock.
ReentrantLock
key features as per this article
You can use ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock
to further acquire control on granular locking on read and write operations.
Apart from these three ReentrantLocks, java 8 provides one more Lock
StampedLock:
Java 8 ships with a new kind of lock called StampedLock which also support read and write locks just like in the example above. In contrast to ReadWriteLock the locking methods of a StampedLock return a stamp represented by a long value.
You can use these stamps to either release a lock or to check if the lock is still valid. Additionally stamped locks support another lock mode called optimistic locking.
Have a look at this article on usage of different type of ReentrantLock
and StampedLock
locks.
Cross Platform, Python 2/3 code:
# import sys, os
def wait_key():
''' Wait for a key press on the console and return it. '''
result = None
if os.name == 'nt':
import msvcrt
result = msvcrt.getch()
else:
import termios
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
try:
result = sys.stdin.read(1)
except IOError:
pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
return result
I removed the fctl/non-blocking stuff because it was giving IOError
s and I didn't need it. I'm using this code specifically because I want it to block. ;)
Addendum:
I implemented this in a package on PyPI with a lot of other goodies called console:
>>> from console.utils import wait_key
>>> wait_key()
'h'
Just replace -H
with -h
. Check man grep
for more details on options
find . -name '*.bar' -exec grep -hn FOO {} \;
Just add a Label without text and with background color. Set the Coordinates of your choice and also height and width. You can do it manually or with Interface Builder.
I got the "No signing certificate" error when running Xcode 11.3 on macOS 10.14.x Mojave. (but after Xcode 12 was released.)
I was also using Fastlane. My fix was to set generate_apple_certs
to false
when running Match. This seemed to generate signing certificates that were backwards-compatible with Xcode 11.3
Match documentation - https://docs.fastlane.tools/actions/match/
This is the relevant section of my Fastfile:
platform :ios do
lane :certs do
force = false
match(type: "development", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.dev")
match(type: "adhoc", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.beta")
match(type: "appstore", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier")
end
...
Maybe something like this:
import matplotlib.pyplot
import pylab
x = [1,2,3,4]
y = [3,4,8,6]
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
EDIT:
Let me see if I understand you correctly now:
You have:
test1 | test2 | test3
test3 | 1 | 0 | 1
test4 | 0 | 1 | 0
test5 | 1 | 1 | 0
Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.
Let's say you results are stored in a 2-D list:
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
We want to transform them into two variables so we are able to plot them.
And I believe this code will give you what you are looking for:
import matplotlib
import pylab
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
x = []
y = []
for ind_1, sublist in enumerate(results):
for ind_2, ele in enumerate(sublist):
if ele == 1:
x.append(ind_1)
y.append(ind_2)
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
Notice that I do need to import pylab
, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.
When you have three columns : first_name, last_name, mid_name:
SELECT CASE
WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
CONCAT_WS( " ", first_name, last_name )
ELSE
CONCAT_WS( " ", first_name, mid_name, last_name )
END
FROM USER;
Copy of one list into second is quite simple , you can do that as below:-
ArrayList<List1> list1= new ArrayList<>();
ArrayList<List1> list2= new ArrayList<>();
//this will your copy your list1 into list2
list2.addAll(list1);
if you have neccessary .net
framework installed. Ex ; .Net 4.0
or .Net 3.5
, then you can just copy Gacutil.exe
from any of the machine and to the new machine.
1) Open CMD as adminstrator in new server.
2) Traverse to the folder where you copied the Gacutil.exe. For eg - C:\program files.(in my case).
3) Type the below in the cmd prompt and install.
C:\Program Files\gacutil.exe /I dllname