Create JPA EntityManager without persistence.xml configuration file
Yes you can without using any xml file using spring like this inside a @Configuration class (or its equivalent spring config xml):
@Bean
public LocalContainerEntityManagerFactoryBean emf(){
properties.put("javax.persistence.jdbc.driver", dbDriverClassName);
properties.put("javax.persistence.jdbc.url", dbConnectionURL);
properties.put("javax.persistence.jdbc.user", dbUser); //if needed
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setPersistenceProviderClass(org.eclipse.persistence.jpa.PersistenceProvider.class); //If your using eclipse or change it to whatever you're using
emf.setPackagesToScan("com.yourpkg"); //The packages to search for Entities, line required to avoid looking into the persistence.xml
emf.setPersistenceUnitName(SysConstants.SysConfigPU);
emf.setJpaPropertyMap(properties);
emf.setLoadTimeWeaver(new ReflectiveLoadTimeWeaver()); //required unless you know what your doing
return emf;
}
Why do I need to configure the SQL dialect of a data source?
Hibernate.dialect
property tells Hibernate to generate the appropriate SQL statements for the chosen database.
A list of available dialects can be found here: http://javamanikandan.blogspot.in/2014/05/sql-dialects-in-hibernate.html
RDBMS Dialect
DB2 org.hibernate.dialect.DB2Dialect
DB2 AS/400 org.hibernate.dialect.DB2400Dialect
DB2 OS390 org.hibernate.dialect.DB2390Dialect
PostgreSQL org.hibernate.dialect.PostgreSQLDialect
MySQL org.hibernate.dialect.MySQLDialect
MySQL with InnoDB org.hibernate.dialect.MySQLInnoDBDialect
MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect
Oracle (any version) org.hibernate.dialect.OracleDialect
Oracle 9i/10g org.hibernate.dialect.Oracle9Dialect
Sybase org.hibernate.dialect.SybaseDialect
Sybase Anywhere org.hibernate.dialect.SybaseAnywhereDialect
Microsoft SQL Server org.hibernate.dialect.SQLServerDialect
SAP DB org.hibernate.dialect.SAPDBDialect
Informix org.hibernate.dialect.InformixDialect
HypersonicSQL org.hibernate.dialect.HSQLDialect
Ingres org.hibernate.dialect.IngresDialect
Progress org.hibernate.dialect.ProgressDialect
Mckoi SQL org.hibernate.dialect.MckoiDialect
Interbase org.hibernate.dialect.InterbaseDialect
Pointbase org.hibernate.dialect.PointbaseDialect
FrontBase org.hibernate.dialect.FrontbaseDialect
Firebird org.hibernate.dialect.FirebirdDialect
Visual Studio loading symbols
Configure in Tools, Options, Debugging, Symbols.
You can watch the output window (view, output) to see what it's doing usually. If it's really slow that probably means it's hitting a symbol server, probably Microsoft's, to download missing symbols. This takes three HTTP hits for each file it can't find on every startup - you can sometimes see this in the status bar at the bottom or in e.g. Fiddler. You can see which modules have loaded symbols in Debug, Windows, Modules whilst you're debugging.
Symbols mean you get useful stack trace information into third party and system assemblies. You definitely need them for your own code, but I think those get loaded regardless. Your best bet is to turn off any non-local symbol sources in that menu and, if you're loading lots of symbols for system assemblies that you don't need to debug into you can temporarily disable loading those to speed up debug start - but they're often useful to have loaded.
Deploying Java webapp to Tomcat 8 running in Docker container
There's a oneliner for this one.
You can simply run,
docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat
This will copy the war file to webapps directory and get your app running in no time.
What does [STAThread] do?
It tells the compiler that you're in a Single Thread Apartment model. This is an evil COM thing, it's usually used for Windows Forms (GUI's) as that uses Win32 for its drawing, which is implemented as STA. If you are using something that's STA model from multiple threads then you get corrupted objects.
This is why you have to invoke onto the Gui from another thread (if you've done any forms coding).
Basically don't worry about it, just accept that Windows GUI threads must be marked as STA otherwise weird stuff happens.
Sending images using Http Post
Version 4.3.5 Updated Code
- httpclient-4.3.5.jar
- httpcore-4.3.2.jar
- httpmime-4.3.5.jar
Since MultipartEntity
has been deprecated. Please see the code below.
String responseBody = "failure";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String url = WWPApi.URL_USERS;
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", String.valueOf(userId));
map.put("action", "update");
url = addQueryParams(map, url);
HttpPost post = new HttpPost(url);
post.addHeader("Accept", "application/json");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);
if (career != null)
builder.addTextBody("career", career, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (gender != null)
builder.addTextBody("gender", gender, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (username != null)
builder.addTextBody("username", username, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (email != null)
builder.addTextBody("email", email, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (password != null)
builder.addTextBody("password", password, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (country != null)
builder.addTextBody("country", country, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (file != null)
builder.addBinaryBody("Filedata", file, ContentType.MULTIPART_FORM_DATA, file.getName());
post.setEntity(builder.build());
try {
responseBody = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
// System.out.println("Response from Server ==> " + responseBody);
JSONObject object = new JSONObject(responseBody);
Boolean success = object.optBoolean("success");
String message = object.optString("error");
if (!success) {
responseBody = message;
} else {
responseBody = "success";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
How to split a string by spaces in a Windows batch file?
This works for me (just an extract from my whole script)
choice /C 1234567H /M "Select an option or ctrl+C to cancel"
set _dpi=%ERRORLEVEL%
if "%_dpi%" == "8" call :helpme && goto menu
for /F "tokens=%_dpi%,*" %%1 in ("032 060 064 096 0C8 0FA 12C") do set _dpi=%%1
echo _dpi:%_dpi%:
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
How do I see all foreign keys to a table or column?
If you use InnoDB and defined FK's you could query the information_schema database e.g.:
SELECT * FROM information_schema.TABLE_CONSTRAINTS
WHERE information_schema.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY'
AND information_schema.TABLE_CONSTRAINTS.TABLE_SCHEMA = 'myschema'
AND information_schema.TABLE_CONSTRAINTS.TABLE_NAME = 'mytable';
How do you synchronise projects to GitHub with Android Studio?
For Android Studio 0.8.9: VCS --> Import into version contraol --> Share project on Github.
It doesn't give you option to share in a specific repository or at least I couldn't find (my limitation!).
You can add your github info here: File --> Settings --> Version COntraol --> Github.
Tomcat is not deploying my web project from Eclipse
In my case, I configured an external Maven installation, and I made sure to be using a JDK instead of a JRE (in the eclipse configuration, and in the Server Environment). You can run a Maven Build of the project from eclipse to check everything is working ok.
After that, I updated the maven projects, cleaned and built the projects, cleaned the server, and redeployed the artifacts.
Saving a select count(*) value to an integer (SQL Server)
If @myInt is zero it means no rows in the table: it would be NULL if never set at all.
COUNT will always return a row, even for no rows in a table.
Edit, Apr 2012: the rules for this are described in my answer here:Does COUNT(*) always return a result?
Your count/assign is correct but could be either way:
select @myInt = COUNT(*) from myTable
set @myInt = (select COUNT(*) from myTable)
However, if you are just looking for the existence of rows, (NOT) EXISTS is more efficient:
IF NOT EXISTS (SELECT * FROM myTable)
Read CSV file column by column
Finds all files in folder and write that data to ArrayList row.
Initialize
ArrayList<ArrayList<String>> row=new ArrayList<ArrayList<String>>();
BufferedReader br=null;
For Accessing row
for(ArrayList<String> data:row){
data.get(col no);
}
or row.get(0).get(0) // getting first row first col
Functions that reads all files from folders and concatenate them row.
static void readData(){
String path="C:\\Users\\Galaxy Computers\\Desktop\\Java project\\Nasdaq\\";
File files=new File(path);
String[] list=files.list();
try {
String sCurrentLine;
char check;
for(String filename:list){
br = new BufferedReader(new FileReader(path+filename));
br.readLine();//If file contains uneccessary first line.
while ((sCurrentLine = br.readLine()) != null) {
row.add(splitLine(sCurrentLine));
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
static ArrayList<String> splitLine(String line){
String[] ar=line.split(",");
ArrayList<String> d=new ArrayList<String>();
for(String data:ar){
d.add(data);
}
return d;
}
How do I compare two strings in Perl?
cmp
Compare
'a' cmp 'b' # -1
'b' cmp 'a' # 1
'a' cmp 'a' # 0
eq
Equal to
'a' eq 'b' # 0
'b' eq 'a' # 0
'a' eq 'a' # 1
ne
Not-Equal to
'a' ne 'b' # 1
'b' ne 'a' # 1
'a' ne 'a' # 0
lt
Less than
'a' lt 'b' # 1
'b' lt 'a' # 0
'a' lt 'a' # 0
le
Less than or equal to
'a' le 'b' # 1
'b' le 'a' # 0
'a' le 'a' # 1
gt
Greater than
'a' gt 'b' # 0
'b' gt 'a' # 1
'a' gt 'a' # 0
ge
Greater than or equal to
'a' ge 'b' # 0
'b' ge 'a' # 1
'a' ge 'a' # 1
See perldoc perlop
for more information.
( I'm simplifying this a little bit as all but cmp
return a value that is both an empty string, and a numerically zero value instead of 0
, and a value that is both the string '1'
and the numeric value 1
. These are the same values you will always get from boolean operators in Perl. You should really only be using the return values for boolean or numeric operations, in which case the difference doesn't really matter. )
Fix columns in horizontal scrolling
Demo: http://www.jqueryscript.net/demo/jQuery-Plugin-For-Fixed-Table-Header-Footer-Columns-TableHeadFixer/
HTML
<h2>TableHeadFixer Fix Left Column</h2>
<div id="parent">
<table id="fixTable" class="table">
<thead>
<tr>
<th>Ano</th>
<th>Jan</th>
<th>Fev</th>
<th>Mar</th>
<th>Abr</th>
<th>Maio</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
</tbody>
</table>
</div>
JS
$(document).ready(function() {
$("#fixTable").tableHeadFixer({"head" : false, "right" : 1});
});
CSS
#parent {
height: 300px;
}
#fixTable {
width: 1800px !important;
}
https://jsfiddle.net/5gfuqqc4/
JavaScript function to add X months to a date
I changed the accepted answer a bit to keep the original date intact, as I think it should in a function like this.
_x000D_
_x000D_
function addMonths(date, months) {
let newDate = new Date(date);
var day = newDate.getDate();
newDate.setMonth(newDate.getMonth() + +months);
if (newDate.getDate() != day)
newDate.setDate(0);
return newDate;
}
_x000D_
_x000D_
_x000D_
Create list of single item repeated N times
Create List of Single Item Repeated n Times in Python
Depending on your use-case, you want to use different techniques with different semantics.
Multiply a list for Immutable items
For immutable items, like None, bools, ints, floats, strings, tuples, or frozensets, you can do it like this:
[e] * 4
Note that this is usually only used with immutable items (strings, tuples, frozensets, ) in the list, because they all point to the same item in the same place in memory. I use this frequently when I have to build a table with a schema of all strings, so that I don't have to give a highly redundant one to one mapping.
schema = ['string'] * len(columns)
Multiply the list where we want the same item repeated
Multiplying a list gives us the same elements over and over. The need for this is rare:
[iter(iterable)] * 4
This is sometimes used to map an iterable into a list of lists:
>>> iterable = range(12)
>>> a_list = [iter(iterable)] * 4
>>> [[next(l) for l in a_list] for i in range(3)]
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
We can see that a_list
contains the same range iterator four times:
>>> a_list
[<range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>]
Mutable items
I've used Python for a long time now, and I have seen very few use-cases where I would do the above with mutable objects.
Instead, to get, say, a mutable empty list, set, or dict, you should do something like this:
list_of_lists = [[] for _ in columns]
The underscore is simply a throwaway variable name in this context.
If you only have the number, that would be:
list_of_lists = [[] for _ in range(4)]
The _
is not really special, but your coding environment style checker will probably complain if you don't intend to use the variable and use any other name.
Caveats for using the immutable method with mutable items:
Beware doing this with mutable objects, when you change one of them, they all change because they're all the same object:
foo = [[]] * 4
foo[0].append('x')
foo now returns:
[['x'], ['x'], ['x'], ['x']]
But with immutable objects, you can make it work because you change the reference, not the object:
>>> l = [0] * 4
>>> l[0] += 1
>>> l
[1, 0, 0, 0]
>>> l = [frozenset()] * 4
>>> l[0] |= set('abc')
>>> l
[frozenset(['a', 'c', 'b']), frozenset([]), frozenset([]), frozenset([])]
But again, mutable objects are no good for this, because in-place operations change the object, not the reference:
l = [set()] * 4
>>> l[0] |= set('abc')
>>> l
[set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b'])]
Excel date to Unix timestamp
If we assume the date in Excel is in A1 cell formatted as Date and the Unix timestamp should be in a A2 cell formatted as number the formula in A2 should be:
= (A1 * 86400) - 2209075200
where:
86400 is the number of seconds in the day
2209075200 is the number of seconds between 1900-01-01 and 1970-01-01 which are the base dates for Excel and Unix timestamps.
The above is true for Windows. On Mac the base date in Excel is 1904-01-01 and the seconds number should be corrected to: 2082844800
How to add Options Menu to Fragment in Android
I had the same problem, but I think it's better to summarize and introduce the last step to get it working:
Add setHasOptionsMenu(true) method in your Fragment's onCreate(Bundle savedInstanceState)
method.
Override onCreateOptionsMenu(Menu menu, MenuInflater inflater)
(if you want to do something different in your Fragment's menu) and onOptionsItemSelected(MenuItem item)
methods in your Fragment.
Inside your onOptionsItemSelected(MenuItem item)
Activity's method, make sure you return false when the menu item action would be implemented in onOptionsItemSelected(MenuItem item)
Fragment's method.
An example:
Activity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.activity_menu_item:
// Do Activity menu item stuff here
return true;
case R.id.fragment_menu_item:
// Not implemented here
return false;
default:
break;
}
return false;
}
Fragment
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
....
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Do something that differs the Activity's menu here
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.activity_menu_item:
// Not implemented here
return false;
case R.id.fragment_menu_item:
// Do Fragment menu item stuff here
return true;
default:
break;
}
return false;
}
Updating a java map entry
You just use the method
public Object put(Object key, Object value)
if the key was already present in the Map then the previous value is returned.
convert HTML ( having Javascript ) to PDF using JavaScript
With Docmosis or JODReports you could feed your HTML and Javascript to the document render process which could produce PDF or doc or other formats. The conversion underneath is performed by OpenOffice so results will be dependent on the OpenOffice import filters. You can try manually by saving your web page to a file, then loading with OpenOffice - if that looks good enough, then these tools will be able to give you the same result as a PDF.
How to convert a normal Git repository to a bare one?
i've read the answers and i have done this:
cd repos
mv .git repos.git
cd repos.git
git config --bool core.bare true # from another answer
cd ../
mv repos.git ../
cd ../
rm -rf repos/ # or delete using a file manager if you like
this will leave the contents of repos/.git
as the bare repos.git
What's the difference between 'r+' and 'a+' when open file in python?
Python opens files almost in the same way as in C:
r+
Open for reading and writing. The stream is positioned at the beginning of the file.
a+
Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is appended to the end of the file (but in some Unix systems regardless of the current seek position).
jQuery changing css class to div
This may not be exactly on target because I am not completely clear on what you want to do. However, assuming you mean you want to assign a different class to a div in response to an event, the answer is yes, you can certainly do this with jQuery. I am only a jQuery beginner, but I have used the following in my code:
$(document).ready(function() {
$("#someElementID").click(function() { // this is your event
$("#divID").addClass("second"); // here your adding the new class
)};
)};
If you wanted to replace the first class with the second class, I believe you would use removeClass first and then addClass as I did above. toggleClass may also be worth a look. The jQuery documentation is well written for these type of changes, with examples.
Someone else my have a better option, but I hope that helps!
Moment.js: Date between dates
Please use the 4th parameter of moment.isBetween function (inclusivity). Example:
var startDate = moment("15/02/2013", "DD/MM/YYYY");
var endDate = moment("20/02/2013", "DD/MM/YYYY");
var testDate = moment("15/02/2013", "DD/MM/YYYY");
testDate.isBetween(startDate, endDate, 'days', true); // will return true
testDate.isBetween(startDate, endDate, 'days', false); // will return false
Difference in boto3 between resource, client, and session?
I'll try and explain it as simple as possible. So there is no guarantee of the accuracy of the actual terms.
Session is where to initiate the connectivity to AWS services. E.g. following is default session that uses the default credential profile(e.g. ~/.aws/credentials, or assume your EC2 using IAM instance profile )
sqs = boto3.client('sqs')
s3 = boto3.resource('s3')
Because default session is limit to the profile or instance profile used, sometimes you need to use the custom session to override the default session configuration (e.g. region_name, endpoint_url, etc. ) e.g.
# custom resource session must use boto3.Session to do the override
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource('s3')
video_s3 = my_east_session.resource('s3')
# you have two choices of create custom client session.
backup_s3c = my_west_session.client('s3')
video_s3c = boto3.client("s3", region_name = 'us-east-1')
Resource : This is the high-level service class recommended to be used. This allows you to tied particular AWS resources and passes it along, so you just use this abstraction than worry which target services are pointed to. As you notice from the session part, if you have a custom session, you just pass this abstract object than worrying about all custom regions,etc to pass along. Following is a complicated example
E.g.
import boto3
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource("s3")
video_s3 = my_east_session.resource("s3")
backup_bucket = backup_s3.Bucket('backupbucket')
video_bucket = video_s3.Bucket('videobucket')
# just pass the instantiated bucket object
def list_bucket_contents(bucket):
for object in bucket.objects.all():
print(object.key)
list_bucket_contents(backup_bucket)
list_bucket_contents(video_bucket)
Client is a low level class object. For each client call, you need to explicitly specify the targeting resources, the designated service target name must be pass long. You will lose the abstraction ability.
For example, if you only deal with the default session, this looks similar to boto3.resource.
import boto3
s3 = boto3.client('s3')
def list_bucket_contents(bucket_name):
for object in s3.list_objects_v2(Bucket=bucket_name) :
print(object.key)
list_bucket_contents('Mybucket')
However, if you want to list objects from a bucket in different regions, you need to specify the explicit bucket parameter required for the client.
import boto3
backup_s3 = my_west_session.client('s3',region_name = 'us-west-2')
video_s3 = my_east_session.client('s3',region_name = 'us-east-1')
# you must pass boto3.Session.client and the bucket name
def list_bucket_contents(s3session, bucket_name):
response = s3session.list_objects_v2(Bucket=bucket_name)
if 'Contents' in response:
for obj in response['Contents']:
print(obj['key'])
list_bucket_contents(backup_s3, 'backupbucket')
list_bucket_contents(video_s3 , 'videobucket')
Split text with '\r\n'
In Winform App(C#):
static string strFilesLoc = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), @"..\..\")) + "Resources\\";
public static string[] GetFontFamily()
{
var result = File.ReadAllText(strFilesLoc + "FontFamily.txt").Trim();
string[] items = result.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
return items;
}
In-text file(FontFamily.txt):
Microsoft Sans Serif
9
true
How to install SQL Server Management Studio 2008 component only
I am just updating this with Microsoft SQL Server Management Studio 2008 R2 version. if you run the installer normally, you can just add Management Tools – Basic, and by clicking Basic it should select Management Tools – Complete.
That is what worked for me.
How do I align a number like this in C?
[I realize this question is a million years old, but there is a deeper question (or two) at its heart, about OP, the pedagogy of programming, and about assumption-making.]
A few people, including a mod, have suggested this is impossible. And, in some--including the most obvious--contexts, it is. But it's interesting to see that that wasn't immediately obvious to the OP.
The impossibility assumes that the contex is running an executable compiled from C on a line-oriented text console (e.g., console+sh or X-term+csh or Terminal+bash), which is a very reasonable assumption. But the fact that the "right" answer ("%8d
") wasn't good enough for OP while also being non-obvious suggests that there's a pretty big can of worms nearby...
Consider Curses (and its many variants). In it, you can navigate the "screen", and "move" the cursor around, and "repaint" portions (windows) of text-based output. In a Curses context, it absolutely would be possible to do; i.e., dynamically resize a "window" to accommodate a larger number. But even Curses is just a screen "painting" abstraction. No one suggested it, and probably rightfully so, because a Curses implementation in C doesn't mean it's "strictly C". Fine.
But what does this really mean? In order for the response: "it's impossible" to be correct, it would mean that we're saying something about the runtime system. In other words, this isn't theoretical, (as in, "How do I sort a statically-allocated array of int
s?"), which can be explained as a "closed system" that totally ignores any aspect of the runtime.
But, in this case, we have I/O: specifically, the implementation of printf()
. But that's where there's an opportunity to have said something more interesting in response (even though, admittedly, the asker was probably not digging quite this deep).
Suppose we use a different set of assumptions. Suppose OP is reasonably "clever" and understands that it would not be possible to to edit previous lines on a line-oriented stream (how would you correct the horizontal position of a character output by a line-printer??). Suppose also, that OP isn't just a kid working on a homework assignment and not realizing it was a "trick" question, intended to tease out an exploration of the meaning of "stream abstraction". Further, let's suppose OP was wondering: "Wait...If C's runtime environment supports the idea of STDOUT--and if STDOUT is just an abstraction--why isn't it just as reasonable to have a terminal abstraction that 1) can vertically scroll but 2) supports a positionable cursor? Both are moving text on a screen."
Because if that were the question we're trying to answer, then you'd only have to look as far as:
ANSI Escape Codes
to see that:
Almost all manufacturers of video terminals added vendor-specific escape sequences to perform operations such as placing the cursor at arbitrary positions on the screen. One example is the VT52 terminal, which allowed the cursor to be placed at an x,y location on the screen by sending the ESC character, a Y character, and then two characters representing with numerical values equal to the x,y location plus 32 (thus starting at the ASCII space character and avoiding the control characters). The Hazeltine 1500 had a similar feature, invoked using ~, DC1 and then the X and Y positions separated with a comma. While the two terminals had identical functionality in this regard, different control sequences had to be used to invoke them.
The first popular video terminal to support these sequences was the Digital VT100, introduced in 1978. This model was very successful in the market, which sparked a variety of VT100 clones, among the earliest and most popular of which was the much more affordable Zenith Z-19 in 1979. Others included the Qume QVT-108, Televideo TVI-970, Wyse WY-99GT as well as optional "VT100" or "VT103" or "ANSI" modes with varying degrees of compatibility on many other brands. The popularity of these gradually led to more and more software (especially bulletin board systems and other online services) assuming the escape sequences worked, leading to almost all new terminals and emulator programs supporting them.
It has been possible, as early as 1978. C itself was "born" in 1972, and the K&R version was established in 1978. If "ANSI" escape sequences were around at that time, then there is an answer "in C" if we're willing to also stipulate: "Well, assuming your terminal is VT100-capable." Incidentally, the consoles which don't support ANSI escapes? You guessed it: Windows & DOS consoles. But on almost every other platform (Unices, Vaxen, Mac OS, Linux) you can expect to.
TL;DR - There is no reasonable answer that can be given without stating assumptions about the runtime environment. Since most runtimes (unless you're using desktop-computer-market-share-of-the-80's-and-90's to calculate 'most') would have, (since the time of the VT-52!), then I don't think it's entirely justified to say that it's impossible--just that in order for it to be possible, it's an entire different order of magnitude of work, and not as simple as %8d
...which it kinda seemed like the OP knew about.
We just have to clarify the assumptions.
And lest one thinks that I/O is exceptional, i.e., the only time we need to think about the runtime, (or even the hardware), just dig into IEEE 754 Floating Point exception handling. For those interested:
Intel Floating Point Case Study
According to Professor William Kahan, University of California at
Berkeley, a classic case occurred in June 1996. A satellite-lifting
rocket named Ariane 5 turned cartwheels shortly after launch and
scattered itself and a payload worth over half a billion dollars over
a marsh in French Guiana. Kahan found the disaster could be blamed
upon a programming language that disregarded the default
exception-handling specifications in IEEE 754. Upon launch, sensors
reported acceleration so strong that it caused a conversion-to-integer
overflow in software intended for recalibration of the rocket’s
inertial guidance while on the launching pad.
Declare a const array
Yes, but you need to declare it readonly
instead of const
:
public static readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
The reason is that const
can only be applied to a field whose value is known at compile-time. The array initializer you've shown is not a constant expression in C#, so it produces a compiler error.
Declaring it readonly
solves that problem because the value is not initialized until run-time (although it's guaranteed to have initialized before the first time that the array is used).
Depending on what it is that you ultimately want to achieve, you might also consider declaring an enum:
public enum Titles { German, Spanish, Corrects, Wrongs };
How to use sed/grep to extract text between two words?
This might work for you (GNU sed):
sed '/Here/!d;s//&\n/;s/.*\n//;:a;/String/bb;$!{n;ba};:b;s//\n&/;P;D' file
This presents each representation of text between two markers (in this instance Here
and String
) on a newline and preserves newlines within the text.
Bootstrap 4 Dropdown Menu not working?
I used NuGet to install BootStrap 4. I was also having issues with it not displaying the Dropdown on click. It kept throwing an error in jquery base on what the Chrome console was telling me.
I originally had the following
<%-- CSS --%>
<link type="text/css" rel="stylesheet" href="/Content/bootstrap.css" />
<%-- JS --%>
<script type="text/javascript" src="/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/Scripts/bootstrap.min.js"></script>
But I changed it to use the bundled version instead and it started to work
<%-- CSS --%>
<link type="text/css" rel="stylesheet" href="/Content/bootstrap.css" />
<%-- JS --%>
<script type="text/javascript" src="/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/Scripts/bootstrap.bundle.min.js"></script>
SOAP or REST for Web Services?
REST is an architecture, SOAP is a protocol.
That's the first problem.
You can send SOAP envelopes in a REST application.
SOAP itself is actually pretty basic and simple, it's the WSS-* standards on top of it that make it very complex.
If your consumers are other applications and other servers, there's a lot of support for the SOAP protocol today, and the basics of moving data is essentially a mouse-click in modern IDEs.
If your consumers are more likely to be RIAs or Ajax clients, you will probably want something simpler than SOAP, and more native to the client (notably JSON).
JSON packets sent over HTTP is not necessarily a REST architecture, it's just messages to URLs. All perfectly workable, but there are key components to the REST idiom. It is easy to confuse the two however. But just because you're talking HTTP requests does not necessarily mean you have a REST architecture. You can have a REST application with no HTTP at all (mind, this is rare).
So, if you have servers and consumers that are "comfortable" with SOAP, SOAP and WSS stack can serve you well. If you're doing more ad hoc things and want to better interface with web browsers, then some lighter protocol over HTTP can work well also.
What's the difference between git clone --mirror and git clone --bare
$ git clone --bare https://github.com/example
This command will make the new "example
" directory itself the $GIT_DIR (instead of example/.git
). Also the branch heads at the remote are copied directly to corresponding local branch heads, without mapping. When this option is used, neither remote-tracking branches nor the related configuration variables are created.
$ git clone --mirror https://github.com/example
As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references (including remote-tracking branches, notes etc.) will be overwritten each time you fetch, so it will always be the same as the original repository.
Combining CSS Pseudo-elements, ":after" the ":last-child"
Adding another answer to this question because I needed precisely what @derek was asking for and I'd already gotten a bit further before seeing the answers here. Specifically, I needed CSS that could also account for the case with exactly two list items, where the comma is NOT desired. As an example, some authorship bylines I wanted to produce would look like the following:
One author:
By Adam Smith.
Two authors:
By Adam Smith and Jane Doe.
Three authors:
By Adam Smith, Jane Doe, and Frank Underwood.
The solutions already given here work for one author and for 3 or more authors, but neglect to account for the two author case—where the "Oxford Comma" style (also known as "Harvard Comma" style in some parts) doesn't apply - ie, there should be no comma before the conjunction.
After an afternoon of tinkering, I had come up with the following:
<html>
<head>
<style type="text/css">
.byline-list {
list-style: none;
padding: 0;
margin: 0;
}
.byline-list > li {
display: inline;
padding: 0;
margin: 0;
}
.byline-list > li::before {
content: ", ";
}
.byline-list > li:last-child::before {
content: ", and ";
}
.byline-list > li:first-child + li:last-child::before {
content: " and ";
}
.byline-list > li:first-child::before {
content: "By ";
}
.byline-list > li:last-child::after {
content: ".";
}
</style>
</head>
<body>
<ul class="byline-list">
<li>Adam Smith</li>
</ul>
<ul class="byline-list">
<li>Adam Smith</li><li>Jane Doe</li>
</ul>
<ul class="byline-list">
<li>Adam Smith</li><li>Jane Doe</li><li>Frank Underwood</li>
</ul>
</body>
</html>
It displays the bylines as I've got them above.
In the end, I also had to get rid of any whitespace between li
elements, in order to get around an annoyance: the inline-block property would otherwise leave a space before each comma. There's probably an alternative decent hack for it but that isn't the subject of this question so I'll leave that for someone else to answer.
Fiddle here: http://jsfiddle.net/5REP2/
How to get selected value of a html select with asp.net
If you would use asp:dropdownlist
you could select it easier by testSelect.Text
.
Now you'd have to do a Request.Form["testSelect"]
to get the value after pressed btnTes
.
Hope it helps.
EDIT: You need to specify a name
of the select (not only ID) to be able to Request.Form["testSelect"]
Inline CSS styles in React: how to implement a:hover?
<Hoverable hoverStyle={styles.linkHover}>
<a href="https://example.com" style={styles.link}>
Go
</a>
</Hoverable>
Where Hoverable is defined as:
function Hoverable(props) {
const [hover, setHover] = useState(false);
const child = Children.only(props.children);
const onHoverChange = useCallback(
e => {
const name = e.type === "mouseenter" ? "onMouseEnter" : "onMouseLeave";
setHover(!hover);
if (child.props[name]) {
child.props[name](e);
}
},
[setHover, hover, child]
);
return React.cloneElement(child, {
onMouseEnter: onHoverChange,
onMouseLeave: onHoverChange,
style: Object.assign({}, child.props.style, hover ? props.hoverStyle : {})
});
}
Full path from file input using jQuery
You can't: It's a security feature in all modern browsers.
For IE8, it's off by default, but can be reactivated using a security setting:
When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.
The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.
In all other current mainstream browsers I know of, it is also turned off. The file name is the best you can get.
More detailed info and good links in this question. It refers to getting the value server-side, but the issue is the same in JavaScript before the form's submission.
How to obtain values of request variables using Python and Flask
If you want to retrieve POST data:
first_name = request.form.get("firstname")
If you want to retrieve GET (query string) data:
first_name = request.args.get("firstname")
Or if you don't care/know whether the value is in the query string or in the post data:
first_name = request.values.get("firstname")
request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.
How do I upgrade the Python installation in Windows 10?
Every minor version of Python, that is any 3.x and 2.x version, will install side-by-side with other versions on your computer. Only patch versions will upgrade existing installations.
So if you want to keep your installed Python 2.7 around, then just let it and install a new version using the installer. If you want to get rid of Python 2.7, you can uninstall it before or after installing a newer version—there is no difference to this.
Current Python 3 installations come with the py.exe
launcher, which by default is installed into the system directory. This makes it available from the PATH, so you can automatically run it from any shell just by using py
instead of python
as the command. This avoids you having to put the current Python installation into PATH yourself. That way, you can easily have multiple Python installations side-by-side without them interfering with each other. When running, just use py script.py
instead of python script.py
to use the launcher. You can also specify a version using for example py -3
or py -3.6
to launch a specific version, otherwise the launcher will use the current default (which will usually be the latest 3.x).
Using the launcher, you can also run Python 2 scripts (which are often syntax incompatible to Python 3), if you decide to keep your Python 2.7 installation. Just use py -2 script.py
to launch a script.
As for PyPI packages, every Python installation comes with its own folder where modules are installed into. So if you install a new version and you want to use modules you installed for a previous version, you will have to install them first for the new version. Current versions of the installer also offer you to install pip
; it’s enabled by default, so you already have pip
for every installation. Unless you explicitly add a Python installation to the PATH, you cannot just use pip
though. Luckily, you can also simply use the py.exe
launcher for this: py -m pip
runs pip
. So for example to install Beautiful Soup for Python 3.6, you could run py -3.6 -m pip install beautifulsoup4
.
How to get value in the session in jQuery
Assuming you are using this plugin, you are misusing the .set
method. .set
must be passed the name of the key as a string as well as the value. I suppose you meant to write:
$.session.set("userName", $("#uname").val());
This sets the userName
key in session storage to the value of the input, and allows you to retrieve it using:
$.session.get('userName');
How to Find Item in Dictionary Collection?
Sometimes you still need to use FirstOrDefault if you have to do different tests.
If the Key component of your dictionnary is nullable, you can do this:
thisTag = _tags.FirstOrDefault(t => t.Key.SubString(1,1) == 'a');
if(thisTag.Key != null) { ... }
Using FirstOrDefault, the returned KeyValuePair's key and value will both be null if no match is found.
How Can I Truncate A String In jQuery?
Instead of using jQuery, use css property text-overflow:ellipsis
. It will automatically truncate the string.
.truncated { display:inline-block;
max-width:100px;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
Rails - How to use a Helper Inside a Controller
class MyController < ApplicationController
# include your helper
include MyHelper
# or Rails helper
include ActionView::Helpers::NumberHelper
def my_action
price = number_to_currency(10000)
end
end
In Rails 5+ simply use helpers (helpers.number_to_currency(10000))
Error: TypeError: $(...).dialog is not a function
if some reason two versions of jQuery
are loaded (which is not recommended), calling $.noConflict(true)
from the second version will return the globally scoped jQuery
variables to those of the first version.
Some times it could be issue with older version (or not stable version) of JQuery
files
Solution use $.noConflict();
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
$("#opener").click(function() {
$("#dialog1").dialog('open');
});
});
// Code that uses other library's $ can follow here.
</script>
Text inset for UITextField?
I subclased UITextField to handle this that supports left, top, right and bottom inset, and clear button positioning as well.
MRDInsetTextField.h
#import <UIKit/UIKit.h>
@interface MRDInsetTextField : UITextField
@property (nonatomic, assign) CGRect inset;
@end
MRDInsetTextField.m
#import "MRDInsetTextField.h"
@implementation MRDInsetTextField
- (id)init
{
self = [super init];
if (self) {
_inset = CGRectZero;
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
_inset = CGRectZero;
}
return self;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_inset = CGRectZero;
}
return self;
}
- (void)setInset:(CGRect)inset {
_inset = inset;
[self setNeedsLayout];
}
- (CGRect)getRectForBounds:(CGRect)bounds withInset:(CGRect)inset {
CGRect newRect = CGRectMake(
bounds.origin.x + inset.origin.x,
bounds.origin.y + inset.origin.y,
bounds.origin.x + bounds.size.width - inset.origin.x - inset.size.width,
bounds.origin.y + bounds.size.height - inset.origin.y - inset.size.height
);
return newRect;
}
- (CGRect)textRectForBounds:(CGRect)bounds {
return [self getRectForBounds:[super textRectForBounds:bounds] withInset:_inset];
}
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
return [self getRectForBounds:bounds withInset:_inset];
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self getRectForBounds:[super editingRectForBounds:bounds] withInset:_inset];
}
- (CGRect)clearButtonRectForBounds:(CGRect)bounds {
return CGRectOffset([super clearButtonRectForBounds:bounds], -_inset.size.width, _inset.origin.y/2 - _inset.size.height/2);
}
@end
Example of usage where *_someTextField* comes from nib/storyboard view with MRDInsetTextField custom class
[(MRDInsetTextField*)_someTextField setInset:CGRectMake(5, 0, 5, 0)]; // left, top, right, bottom inset
How to force a html5 form validation without submitting it via jQuery
You don't need jQuery to achieve this. In your form add:
onsubmit="return buttonSubmit(this)
or in JavaScript:
myform.setAttribute("onsubmit", "return buttonSubmit(this)");
In your buttonSubmit
function (or whatver you call it), you can submit the form using AJAX. buttonSubmit
will only get called if your form is validated in HTML5.
In case this helps anyone, here is my buttonSubmit
function:
function buttonSubmit(e)
{
var ajax;
var formData = new FormData();
for (i = 0; i < e.elements.length; i++)
{
if (e.elements[i].type == "submit")
{
if (submitvalue == e.elements[i].value)
{
submit = e.elements[i];
submit.disabled = true;
}
}
else if (e.elements[i].type == "radio")
{
if (e.elements[i].checked)
formData.append(e.elements[i].name, e.elements[i].value);
}
else
formData.append(e.elements[i].name, e.elements[i].value);
}
formData.append("javascript", "javascript");
var action = e.action;
status = action.split('/').reverse()[0] + "-status";
ajax = new XMLHttpRequest();
ajax.addEventListener("load", manageLoad, false);
ajax.addEventListener("error", manageError, false);
ajax.open("POST", action);
ajax.send(formData);
return false;
}
Some of my forms contain multiple submit buttons, hence this line if (submitvalue == e.elements[i].value)
. I set the value of submitvalue
using a click event.
Parsing JSON array into java.util.List with Gson
Below code is using com.google.gson.JsonArray
.
I have printed the number of element in list as well as the elements in List
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
static String str = "{ "+
"\"client\":\"127.0.0.1\"," +
"\"servers\":[" +
" \"8.8.8.8\"," +
" \"8.8.4.4\"," +
" \"156.154.70.1\"," +
" \"156.154.71.1\" " +
" ]" +
"}";
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(str);
JsonArray jsonArr = jo.getAsJsonArray("servers");
//jsonArr.
Gson googleJson = new Gson();
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
System.out.println("List size is : "+jsonObjList.size());
System.out.println("List Elements are : "+jsonObjList.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT
List size is : 4
List Elements are : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]
Counting Line Numbers in Eclipse
Are you interested in counting the executable lines rather than the total file line count?
If so you could try a code coverage tool such as EclEmma.
As a side effect of the code coverage stats you get stats on the number of executable lines and blocks (and methods and classes). These are rolled up from the method level upwards, so you can see line counts for the packages, source roots and projects as well.
How can I check if a Perl array contains a particular value?
@eakssjo's benchmark is broken - measures creating hashes in loop vs creating regexes in loop. Fixed version (plus I've added List::Util::first
and List::MoreUtils::any
):
use List::Util qw(first);
use List::MoreUtils qw(any);
use Benchmark;
my @list = ( 1..10_000 );
my $hit = 5_000;
my $hit_regex = qr/^$hit$/; # precompute regex
my %params;
$params{$_} = 1 for @list; # precompute hash
timethese(
100_000, {
'any' => sub {
die unless ( any { $hit_regex } @list );
},
'first' => sub {
die unless ( first { $hit_regex } @list );
},
'grep' => sub {
die unless ( grep { $hit_regex } @list );
},
'hash' => sub {
die unless ( $params{$hit} );
},
});
And result (it's for 100_000 iterations, ten times more than in @eakssjo's answer):
Benchmark: timing 100000 iterations of any, first, grep, hash...
any: 0 wallclock secs ( 0.67 usr + 0.00 sys = 0.67 CPU) @ 149253.73/s (n=100000)
first: 1 wallclock secs ( 0.63 usr + 0.01 sys = 0.64 CPU) @ 156250.00/s (n=100000)
grep: 42 wallclock secs (41.95 usr + 0.08 sys = 42.03 CPU) @ 2379.25/s (n=100000)
hash: 0 wallclock secs ( 0.01 usr + 0.00 sys = 0.01 CPU) @ 10000000.00/s (n=100000)
(warning: too few iterations for a reliable count)
Structuring online documentation for a REST API
That's a very complex question for a simple answer.
You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.
Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.
At the very top level I think quality REST API docs require at least the following:
- a list of all your API endpoints (base/relative URLs)
- corresponding HTTP GET/POST/... method type for each endpoint
- request/response MIME-type (how to encode params and parse replies)
- a sample request/response, including HTTP headers
- type and format specified for all params, including those in the URL, body and headers
- a brief text description and important notes
- a short code snippet showing the use of the endpoint in popular web programming languages
Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.
Java: splitting the filename into a base and extension
Maybe you could use String#split
To answer your comment:
I'm not sure if there can be more than one . in a filename, but whatever, even if there are more dots you can use the split. Consider e.g. that:
String input = "boo.and.foo";
String[] result = input.split(".");
This will return an array containing:
{ "boo", "and", "foo" }
So you will know that the last index in the array is the extension and all others are the base.
File Upload without Form
Sorry for being that guy but AngularJS offers a simple and elegant solution.
Here is the code I use:
_x000D_
_x000D_
ngApp.controller('ngController', ['$upload',_x000D_
function($upload) {_x000D_
_x000D_
$scope.Upload = function($files, index) {_x000D_
for (var i = 0; i < $files.length; i++) {_x000D_
var file = $files[i];_x000D_
$scope.upload = $upload.upload({_x000D_
file: file,_x000D_
url: '/File/Upload',_x000D_
data: {_x000D_
id: 1 //some data you want to send along with the file,_x000D_
name: 'ABC' //some data you want to send along with the file,_x000D_
},_x000D_
_x000D_
}).progress(function(evt) {_x000D_
_x000D_
}).success(function(data, status, headers, config) {_x000D_
alert('Upload done');_x000D_
}_x000D_
})_x000D_
.error(function(message) {_x000D_
alert('Upload failed');_x000D_
});_x000D_
}_x000D_
};_x000D_
}]);
_x000D_
.Hidden {_x000D_
display: none_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div data-ng-controller="ngController">_x000D_
<input type="button" value="Browse" onclick="$(this).next().click();" />_x000D_
<input type="file" ng-file-select="Upload($files, 1)" class="Hidden" />_x000D_
</div>
_x000D_
_x000D_
_x000D_
On the server side I have an MVC controller with an action the saves the files uploaded found in the Request.Files collection and returning a JsonResult.
If you use AngularJS try this out, if you don't... sorry mate :-)
How to get a list of column names
SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'
Then parse this value with Reg Exp (it's easy) which could looks similar to this: [(.*?)]
Alternatively you can use:
PRAGMA table_info(table_name)
What is the difference between a database and a data warehouse?
Data Warehouse vs Database: A data warehouse is specially designed for data analytics, which involves reading large amounts of data to understand relationships and trends across the data. A database is used to capture and store data, such as recording details of a transaction.
Data Warehouse:
Suitable workloads - Analytics, reporting, big data.
Data source - Data collected and normalized from many sources.
Data capture - Bulk write operations typically on a predetermined batch schedule.
Data normalization - Denormalized schemas, such as the Star schema or Snowflake schema.
Data storage - Optimized for simplicity of access and high-speed query. performance using columnar storage.
Data access - Optimized to minimize I/O and maximize data throughput.
Transactional Database:
Suitable workloads - Transaction processing.
Data source - Data captured as-is from a single source, such as a transactional system.
Data capture - Optimized for continuous write operations as new data is available to maximize transaction throughput.
Data normalization - Highly normalized, static schemas.
Data storage - Optimized for high throughout write operations to a single row-oriented physical block.
Data access - High volumes of small read operations.
How to explicitly obtain post data in Spring MVC?
If you are using one of the built-in controller instances, then one of the parameters to your controller method will be the Request object. You can call request.getParameter("value1")
to get the POST (or PUT) data value.
If you are using Spring MVC annotations, you can add an annotated parameter to your method's parameters:
@RequestMapping(value = "/someUrl")
public String someMethod(@RequestParam("value1") String valueOne) {
//do stuff with valueOne variable here
}
Sorting a list with stream.sorted() in Java
This is not like Collections.sort()
where the parameter reference gets sorted. In this case you just get a sorted stream that you need to collect and assign to another variable eventually:
List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
compareTo(o2.getItem().getValue())).
collect(Collectors.toList());
You've just missed to assign the result
How to check whether input value is integer or float?
Math.round()
returns the nearest integer to your given input value. If your float already has an integer value the "nearest" integer will be that same value, so all you need to do is check whether Math.round()
changes the value or not:
if (value == Math.round(value)) {
System.out.println("Integer");
} else {
System.out.println("Not an integer");
}
Flask - Calling python function on button OnClick event
It sounds like you want to use this web application as a remote control for your robot, and a core issue is that you won't want a page reload every time you perform an action, in which case, the last link you posted answers your problem.
I think you may be misunderstanding a few things about Flask. For one, you can't nest multiple functions in a single route. You're not making a set of functions available for a particular route, you're defining the one specific thing the server will do when that route is called.
With that in mind, you would be able to solve your problem with a page reload by changing your app.py to look more like this:
from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/forward/", methods=['POST'])
def move_forward():
#Moving forward code
forward_message = "Moving Forward..."
return render_template('index.html', forward_message=forward_message);
Then in your html, use this:
<form action="/forward/" method="post">
<button name="forwardBtn" type="submit">Forward</button>
</form>
...To execute your moving forward code. And include this:
{{ forward_message }}
... where you want the moving forward message to appear on your template.
This will cause your page to reload, which is inevitable without using AJAX and Javascript.
"Series objects are mutable and cannot be hashed" error
Shortly: gene_name[x]
is a mutable object so it cannot be hashed. To use an object as a key in a dictionary, python needs to use its hash value, and that's why you get an error.
Further explanation:
Mutable objects are objects which value can be changed.
For example, list
is a mutable object, since you can append to it. int
is an immutable object, because you can't change it. When you do:
a = 5;
a = 3;
You don't change the value of a
, you create a new object and make a
point to its value.
Mutable objects cannot be hashed. See this answer.
To solve your problem, you should use immutable objects as keys in your dictionary. For example: tuple
, string
, int
.
Is it possible to get element from HashMap by its position?
You can try to implement something like that, look at:
Map<String, Integer> map = new LinkedHashMap<String, Integer>();
map.put("juan", 2);
map.put("pedro", 3);
map.put("pablo", 5);
map.put("iphoncio",9)
List<String> indexes = new ArrayList<String>(map.keySet()); // <== Parse
System.out.println(indexes.indexOf("juan")); // ==> 0
System.out.println(indexes.indexOf("iphoncio")); // ==> 3
I hope this works for you.
Appending output of a Batch file To log file
This is not an answer to your original question: "Appending output of a Batch file To log file?"
For reference, it's an answer to your followup question: "What lines should i add to my batch file which will make it execute after every 30mins?"
(But I would take Jon Skeet's advice: "You probably shouldn't do that in your batch file - instead, use Task Scheduler.")
Timeout:
Example (1 second):
TIMEOUT /T 1000 /NOBREAK
Sleep:
Example (1 second):
sleep -m 1000
Alternative methods:
Here's an answer to your 2nd followup question: "Along with the Timestamp?"
Create a date and time stamp in your batch files
Example:
echo *** Date: %DATE:/=-% and Time:%TIME::=-% *** >> output.log
Android design support library for API 28 (P) not working
Note: You should not use the com.android.support and com.google.android.material dependencies in your app at the same time.
Add Material Components for Android in your build.gradle(app) file
dependencies {
// ...
implementation 'com.google.android.material:material:1.0.0-beta01'
// ...
}
If your app currently depends on the original Design Support Library, you can make use of the Refactor to AndroidX… option provided by Android Studio. Doing so will update your app’s dependencies and code to use the newly packaged androidx and com.google.android.material libraries.
If you don’t want to switch over to the new androidx and com.google.android.material packages yet, you can use Material Components via the com.android.support:design:28.0.0-alpha3 dependency.
Detect touch press vs long press vs movement?
I was just dealing with this mess after wanting longclick to not end with a click event.
Here's what I did.
public boolean onLongClick(View arg0) {
Toast.makeText(getContext(), "long click", Toast.LENGTH_SHORT).show();
longClicked = true;
return false;
}
public void onClick(View arg0) {
if(!longClicked){
Toast.makeText(getContext(), "click", Toast.LENGTH_SHORT).show();
}
longClick = false; // sets the clickability enabled
}
boolean longClicked = false;
It's a bit of a hack but it works.
How can I check if a command exists in a shell script?
A function I have in an install script made for exactly this
function assertInstalled() {
for var in "$@"; do
if ! which $var &> /dev/null; then
echo "Install $var!"
exit 1
fi
done
}
example call:
assertInstalled zsh vim wget python pip git cmake fc-cache
Including one C source file in another?
Including C file into another file is legal, but not advisable thing to do, unless you know exactly why are you doing this and what are you trying to achieve.
I'm almost sure that if you will post here the reason that behind your question the community will find you another more appropriate way to achieve you goal (please note the "almost", since it is possible that this is the solution given the context).
By the way i missed the second part of the question. If C file is included to another file and in the same time included to the project you probably will end up with duplicate symbol problem why linking the objects, i.e same function will be defined twice (unless they all static).
TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"
Two Things you have to care..
If you using the sub module, you have to import the FormModule in that sub module.
**imports:[CommonModule,HttpModule,FormsModule]**
you have to exports the FormModule in the module
**exports:[FormsModule],**
so together it looks like
imports:[CommonModule,HttpModule,FormsModule],
exports:[FormsModule],
in Top u have to import the FormsModule
import {FormsModule} from '@angular/forms';
if you are using only the app.module.ts then
no need to export.. only import required
bootstrap multiselect get selected values
$('#multiselect1').on('change', function(){
var selected = $(this).find("option:selected");
var arrSelected = [];
selected.each(function(){
arrSelected.push($(this).val());
});
});
Make a UIButton programmatically in Swift
Swift 4/5
let button = UIButton(frame: CGRect(x: 20, y: 20, width: 200, height: 60))
button.setTitle("Email", for: .normal)
button.backgroundColor = .white
button.setTitleColor(UIColor.black, for: .normal)
button.addTarget(self, action: #selector(self.buttonTapped), for: .touchUpInside)
myView.addSubview(button)
@objc func buttonTapped(sender : UIButton) {
//Write button action here
}
LINQ to read XML
XDocument xdoc = XDocument.Load("data.xml");
var lv1s = xdoc.Root.Descendants("level1");
var lvs = lv1s.SelectMany(l=>
new string[]{ l.Attribute("name").Value }
.Union(
l.Descendants("level2")
.Select(l2=>" " + l2.Attribute("name").Value)
)
);
foreach (var lv in lvs)
{
result.AppendLine(lv);
}
Ps. You have to use .Root on any of these versions.
Why have header files and .cpp files?
Because C, where the concept originated, is 30 years old, and back then, it was the only viable way to link together code from multiple files.
Today, it's an awful hack which totally destroys compilation time in C++, causes countless needless dependencies (because class definitions in a header file expose too much information about the implementation), and so on.
bootstrap responsive table content wrapping
I ran across the same issue you did but the above answers did not solve my issue. The only way I was able to resolve it - was to make a class and use specific widths to trigger the wrapping for my specific use case. As an example, I provided a snippet below - but I found you will need to adjust it for the table in question - since I typically use multiple colspans depending on the layout. The reasoning I believe Bootstrap is failing - is because it removes the wrapping constraints to get a full table for the scrollbars. THe colspan must be tripping it up.
<style>
@media (max-width: 768px) { /* use the max to specify at each container level */
.specifictd {
width:360px; /* adjust to desired wrapping */
display:table;
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
}
I hope this helps
How can I exclude directories from grep -R?
Frequently use this:
grep
can be used in conjunction with -r
(recursive), i
(ignore case) and -o
(prints only matching part of lines). To exclude files
use --exclude
and to exclude directories use --exclude-dir
.
Putting it together you end up with something like:
grep -rio --exclude={filenames comma separated} \
--exclude-dir={directory names comma separated} <search term> <location>
Describing it makes it sound far more complicated than it actually is. Easier to illustrate with a simple example.
Example:
Suppose I am searching for current project for all places where I explicitly set the string value debugger
during a debugging session, and now wish to review / remove.
I write a script called findDebugger.sh
and use grep
to find all occurrences. However:
For file exclusions - I wish to ensure that .eslintrc
is ignored (this actually has a linting rule about debugger
so should be excluded). Likewise, I don't want my own script to be referenced in any results.
For directory exclusions - I wish to exclude node_modules
as it contains lots of libraries that do reference debugger
and I am not interested in those results. Also I just wish to omit .idea
and .git
hidden directories because I don't care about those search locations either, and wish to keep the search performant.
So here is the result - I create a script called findDebugger.sh
with:
#!/usr/bin/env bash
grep -rio --exclude={.eslintrc,findDebugger.sh} \
--exclude-dir={node_modules,.idea,.git} debugger .
Foreach in a Foreach in MVC View
Controller
public ActionResult Index()
{
//you don't need to include the category bc it does it by itself
//var model = db.Product.Include(c => c.Category).ToList()
ViewBag.Categories = db.Category.OrderBy(c => c.Name).ToList();
var model = db.Product.ToList()
return View(model);
}
View
you need to filter the model with the given category
like :=> Model.where(p=>p.CategoryID == category.CategoryID)
try this...
@foreach (var category in ViewBag.Categories)
{
<h3><u>@category.Name</u></h3>
<div>
@foreach (var product in Model.where(p=>p.CategoryID == category.CategoryID))
{
<table cellpadding="5" cellspacing"5" style="border:1px solid black; width:100%;background-color:White;">
<thead>
<tr>
<th style="background-color:black; color:white;">
@product.Title
@if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
{
@Html.Raw(" - ")
@Html.ActionLink("Edit", "Edit", new { id = product.ID }, new { style = "background-color:black; color:white !important;" })
}
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="background-color:White;">
@product.Description
</td>
</tr>
</tbody>
</table>
}
</div>
}
Count lines in large files
I have a 645GB text file, and none of the earlier exact solutions (e.g. wc -l
) returned an answer within 5 minutes.
Instead, here is Python script that computes the approximate number of lines in a huge file. (My text file apparently has about 5.5 billion lines.) The Python script does the following:
A. Counts the number of bytes in the file.
B. Reads the first N
lines in the file (as a sample) and computes the average line length.
C. Computes A/B as the approximate number of lines.
It follows along the line of Nico's answer, but instead of taking the length of one line, it computes the average length of the first N
lines.
Note: I'm assuming an ASCII text file, so I expect the Python len()
function to return the number of chars as the number of bytes.
Put this code into a file line_length.py
:
#!/usr/bin/env python
# Usage:
# python line_length.py <filename> <N>
import os
import sys
import numpy as np
if __name__ == '__main__':
file_name = sys.argv[1]
N = int(sys.argv[2]) # Number of first lines to use as sample.
file_length_in_bytes = os.path.getsize(file_name)
lengths = [] # Accumulate line lengths.
num_lines = 0
with open(file_name) as f:
for line in f:
num_lines += 1
if num_lines > N:
break
lengths.append(len(line))
arr = np.array(lengths)
lines_count = len(arr)
line_length_mean = np.mean(arr)
line_length_std = np.std(arr)
line_count_mean = file_length_in_bytes / line_length_mean
print('File has %d bytes.' % (file_length_in_bytes))
print('%.2f mean bytes per line (%.2f std)' % (line_length_mean, line_length_std))
print('Approximately %d lines' % (line_count_mean))
Invoke it like this with N
=5000.
% python line_length.py big_file.txt 5000
File has 645620992933 bytes.
116.34 mean bytes per line (42.11 std)
Approximately 5549547119 lines
So there are about 5.5 billion lines in the file.
Appending an element to the end of a list in Scala
We can append or prepend two lists or list&array
Append:
var l = List(1,2,3)
l = l :+ 4
Result : 1 2 3 4
var ar = Array(4, 5, 6)
for(x <- ar)
{ l = l :+ x }
l.foreach(println)
Result:1 2 3 4 5 6
Prepending:
var l = List[Int]()
for(x <- ar)
{ l= x :: l } //prepending
l.foreach(println)
Result:6 5 4 1 2 3
How to convert interface{} to string?
You need to add type assertion .(string)
. It is necessary because the map is of type map[string]interface{}
:
host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)
Latest version of Docopt returns Opts object that has methods for conversion:
host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + port
How do I install the babel-polyfill library?
First off, the obvious answer that no one has provided, you need to install Babel into your application:
npm install babel --save
(or babel-core
if you instead want to require('babel-core/polyfill')
).
Aside from that, I have a grunt task to transpile my es6 and jsx as a build step (i.e. I don't want to use babel/register
, which is why I am trying to use babel/polyfill
directly in the first place), so I'd like to put more emphasis on this part of @ssube's answer:
Make sure you require it at the entry-point to your application,
before anything else is called
I ran into some weird issue where I was trying to require babel/polyfill
from some shared environment startup file and I got the error the user referenced - I think it might have had something to do with how babel orders imports versus requires but I'm unable to reproduce now. Anyway, moving import 'babel/polyfill'
as the first line in both my client and server startup scripts fixed the problem.
Note that if you instead want to use require('babel/polyfill')
I would make sure all your other module loader statements are also requires and not use imports - avoid mixing the two. In other words, if you have any import statements in your startup script, make import babel/polyfill
the first line in your script rather than require('babel/polyfill')
.
How to hide elements without having them take space on the page?
display: none is solution, That's completely hides elements with its space.
visibility:hidden
means the tag is not visible, but space is allocated for it on the page.
display:none
means completely hides elements with its space. (although you can still interact with it through the DOM)
sqlalchemy filter multiple columns
There are number of ways to do it:
Using filter()
(and operator)
query = meta.Session.query(User).filter(
User.firstname.like(search_var1),
User.lastname.like(search_var2)
)
Using filter_by()
(and operator)
query = meta.Session.query(User).filter_by(
firstname.like(search_var1),
lastname.like(search_var2)
)
Chaining filter()
or filter_by()
(and operator)
query = meta.Session.query(User).\
filter_by(firstname.like(search_var1)).\
filter_by(lastname.like(search_var2))
Using or_()
, and_()
, and not()
from sqlalchemy import and_, or_, not_
query = meta.Session.query(User).filter(
and_(
User.firstname.like(search_var1),
User.lastname.like(search_var2)
)
)
Checking if an object is null in C#
I did more simple (positive way) and it seems to work well.
Since any kind of "object" is at least an object
if (MyObj is Object)
{
//Do something .... for example:
if (MyObj is Button)
MyObj.Enabled = true;
}
JSON forEach get Key and Value
Try something like this:
var prop;
for(prop in obj) {
if(!obj.hasOwnProperty(prop)) continue;
console.log(prop + " - "+ obj[prop]);
}
GitHub "fatal: remote origin already exists"
facing same error while add repository to git hun using git bash on windows
git remote add origin https://github.com/axaysushir/netflix_page_clone.git
fatal: remote origin already exists.
fatal: remote origin already exists.
! [rejected] master -> master (fetch first)
error: failed to push some refs to 'https://github.com/axaysushir/meditation_app_using_js.git'
Update repository by following command
$ git remote set-url origin https://github.com/axaysushir/netflix_page_clone.git
then add repository using git remote add github instead git remote add origin
$ git remote add github https://github.com/axaysushir/netflix_page_clone.git
And then write following command instead of git push origin master this will upload your repository to github
$ git push github master
How do I get the Date & Time (VBS)
For VBScript use FormatDateTime, which has 5 numerical arguments to give you one of 5 predefined formats. Its not great.
FormatDateTime(now, 4)
08:12
How to stop a JavaScript for loop?
To stop a for
loop early in JavaScript, you use break
:
var remSize = [],
szString,
remData,
remIndex,
i;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {
// I'm looking for the index i, when the condition is true
if (remSize[i].size === remData.size) {
remIndex = i;
break; // <=== breaks out of the loop early
}
}
If you're in an ES2015 (aka ES6) environment, for this specific use case, you can use Array#findIndex
(to find the entry's index) or Array#find
(to find the entry itself), both of which can be shimmed/polyfilled:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = remSize.findIndex(function(entry) {
return entry.size === remData.size;
});
Array#find
:
var remSize = [],
szString,
remData,
remEntry;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remEntry = remSize.find(function(entry) {
return entry.size === remData.size;
});
Array#findIndex
stops the first time the callback returns a truthy value, returning the index for that call to the callback; it returns -1
if the callback never returns a truthy value. Array#find
also stops when it finds what you're looking for, but it returns the entry, not its index (or undefined
if the callback never returns a truthy value).
If you're using an ES5-compatible environment (or an ES5 shim), you can use the new some
function on arrays, which calls a callback until the callback returns a truthy value:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
if (entry.size === remData.size) {
remIndex = index;
return true; // <== Equivalent of break for `Array#some`
}
});
If you're using jQuery, you can use jQuery.each
to loop through an array; that would look like this:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
if (entry.size === remData.size) {
remIndex = index;
return false; // <== Equivalent of break for jQuery.each
}
});
Markdown: continue numbered list
If you use tab to indent the code block it will shape the entire block into one line. To avoid this you need to use html ordered list.
- item 1
- item 2
Code block
<ol start="3">
<li>item 3</li>
<li>item 4</li>
</ol>
Multiple inputs on one line
Yes, you can.
From cplusplus.com:
Because these functions are operator overloading functions, the usual way in which they are called is:
strm >> variable;
Where strm
is the identifier of a istream object and variable
is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:
strm >> variable1 >> variable2 >> variable3; //...
which is the same as performing successive extractions from the same object strm
.
Just replace strm
with cin
.
No more data to read from socket error
For errors like this you should involve oracle support. Unfortunately you do not mention what oracle release you are using. The error can be related to optimizer bind peeking. Depending on the oracle version different workarounds apply.
You have two ways to address this:
- upgrade to 11.2
- set oracle parameter
_optim_peek_user_binds = false
Of course underscore parameters should only be set if advised by oracle support
How do I create my own URL protocol? (e.g. so://...)
This is different for each browser, in IE and windows you need to create what they call a pluggable protocol handler.
The basic steps are as follows:
- Implement the IInternetProtocol interface.
- Implement the IInternetProtocolRoot interface.
- Implement the IClassFactory interface.
- Optional. Implement the IInternetProtocolInfo interface. Support for the HTTP protocol is provided by the transaction handler.
- If IInternetProtocolInfo is implemented, provide support for PARSE_SECURITY_URL and PARSE_SECURITY_DOMAIN so the URL security zone manager can handle the security properly.
Write the code for your protocol handler.
- Provide support for BINDF_NO_UI and BINDF_SILENTOPERATION.
- Add a subkey for your protocol handler in the registry under HKEY_CLASSES_ROOT\PROTOCOLS\Handler.
- Create a string value, CLSID, under the subkey and set the string to the CLSID of your protocol handler.
See About Asynchronous Pluggable Protocols on MSDN for more details on the windows side. There is also a sample in the windows SDK.
A quick google also showed this article on codeproject: http://www.codeproject.com/KB/IP/DataProtocol.aspx.
Finally, as a security guy I have to point out that this code needs to be battle hardened. It's at a high risk because to do it reliably you can't do it in managed code and have to do it in C++ (I suppose you could use VB6). You should consider whether you really need to do this and if you do, design it carefully and code it securely. An attacker can easily control the content that gets passed to you by simply including a link on a page. For example if you have a simple buffer overflow then nobody better do this: <a href="custom:foooo{insert long string for buffer overflow here}"> Click me for free porn</a>
Strongly consider using strsafe and the new secure CRT methods included in the VC8 and above compilers. See http://blogs.msdn.com/michael_howard/archive/2006/02/27/540123.aspx if you have no idea what I'm talking about.
Capture iOS Simulator video for App Preview
Unfortunately, the iOS Simulator app does not support saving videos. The easiest thing to do is use Quicktime Player to make a screen recording. Of course, you'll see the mouse interacting with it which is not what you want, but I don't have a better option for you at this time.
What's the simplest way to print a Java array?
Prior to Java 8
We could have used Arrays.toString(array)
to print one dimensional array and Arrays.deepToString(array)
for multi-dimensional arrays.
Java 8
Now we have got the option of Stream
and lambda
to print the array.
Printing One dimensional Array:
public static void main(String[] args) {
int[] intArray = new int[] {1, 2, 3, 4, 5};
String[] strArray = new String[] {"John", "Mary", "Bob"};
//Prior to Java 8
System.out.println(Arrays.toString(intArray));
System.out.println(Arrays.toString(strArray));
// In Java 8 we have lambda expressions
Arrays.stream(intArray).forEach(System.out::println);
Arrays.stream(strArray).forEach(System.out::println);
}
The output is:
[1, 2, 3, 4, 5]
[John, Mary, Bob]
1
2
3
4
5
John
Mary
Bob
Printing Multi-dimensional Array
Just in case we want to print multi-dimensional array we can use Arrays.deepToString(array)
as:
public static void main(String[] args) {
int[][] int2DArray = new int[][] { {11, 12}, { 21, 22}, {31, 32, 33} };
String[][] str2DArray = new String[][]{ {"John", "Bravo"} , {"Mary", "Lee"}, {"Bob", "Johnson"} };
//Prior to Java 8
System.out.println(Arrays.deepToString(int2DArray));
System.out.println(Arrays.deepToString(str2DArray));
// In Java 8 we have lambda expressions
Arrays.stream(int2DArray).flatMapToInt(x -> Arrays.stream(x)).forEach(System.out::println);
Arrays.stream(str2DArray).flatMap(x -> Arrays.stream(x)).forEach(System.out::println);
}
Now the point to observe is that the method Arrays.stream(T[])
, which in case of int[]
returns us Stream<int[]>
and then method flatMapToInt()
maps each element of stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
The output is:
[[11, 12], [21, 22], [31, 32, 33]]
[[John, Bravo], [Mary, Lee], [Bob, Johnson]]
11
12
21
22
31
32
33
John
Bravo
Mary
Lee
Bob
Johnson
using nth-child in tables tr td
Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td>
that have $
inside. Example:
using nth-child in tables tr td
html
<tr>
<td> </td>
<td data-rel='$'>$</td>
<td> </td>
</tr>
css
table tr td[data-rel='$'] {
background-color: #333;
color: white;
}
Please try these example.
_x000D_
_x000D_
table tr td[data-content='$'] {_x000D_
background-color: #333;_x000D_
color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<td>A</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>B</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>C</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>D</td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_
how to get current datetime in SQL?
GETDATE()
or GETUTCDATE()
are now superseded by the richer SYSDATETIME
, SYSUTCDATETIME
, and SYSDATETIMEOFFSET
(in SQL 2008)
- Yes, I don't think
ANSI
has ever declared anything, and so each manufacturer has their own.
- That would be
NOW()
Hope this helps...
Rob
Android RatingBar change star colors
I solve this issue this following:
LayerDrawable layerDrawable = (LayerDrawable) ratingBar.getProgressDrawable();
DrawableCompat.setTint(DrawableCompat.wrap(layerDrawable.getDrawable(0)),
Color.WHITE); // Empty star
DrawableCompat.setTint(DrawableCompat.wrap(layerDrawable.getDrawable(1)),
Color.YELLOW); // Partial star
DrawableCompat.setTint(DrawableCompat.wrap(layerDrawable.getDrawable(2)),
Color.YELLOW);
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
I would suggest this simplest solution to use Object.entries()
_x000D_
_x000D_
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}_x000D_
var result =Object.entries(obj)_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_
Selecting multiple items in ListView
In listView you can use it by Adapter
ArrayAdapter<String> adapterChannels = new ArrayAdapter<>(this, android.R.layout.simple_list_item_multiple_choice);
How do you use the Immediate Window in Visual Studio?
One nice feature of the Immediate Window in Visual Studio is its ability to evaluate the return value of a method particularly if it is called by your client code but it is not part of a variable assignment. In Debug mode, as mentioned, you can interact with variables and execute expressions in memory which plays an important role in being able to do this.
For example, if you had a static method that returns the sum of two numbers such as:
private static int GetSum(int a, int b)
{
return a + b;
}
Then in the Immediate Window you can type the following:
? GetSum(2, 4)
6
As you can seen, this works really well for static methods. However, if the method is non-static then you need to interact with a reference to the object the method belongs to.
For example, let’s say this is what your class looks like:
private class Foo
{
public string GetMessage()
{
return "hello";
}
}
If the object already exists in memory and it’s in scope, then you can call it in the Immediate Window as long as it has been instantiated before your current breakpoint (or, at least, before wherever the code is paused in debug mode):
? foo.GetMessage(); // object ‘foo’ already exists
"hello"
In addition, if you want to interact and test the method directly without relying on an existing instance in memory, then you can instantiate your own instance in the Immediate Window:
? Foo foo = new Foo(); // new instance of ‘Foo’
{temp.Program.Foo}
? foo.GetMessage()
"hello"
You can take it a step further and temporarily assign the method's results to variables if you want to do further evaluations, calculations, etc.:
? string msg = foo.GetMessage();
"hello"
? msg + " there!"
"hello there!"
Furthermore, if you don’t even want to declare a variable name for a new object and just want to run one of its methods/functions then do this:
? new Foo().GetMessage()
"hello"
A very common way to see the value of a method is to select the method name of a class and do a ‘Add Watch’ so that you can see its current value in the Watch window. However, once again, the object needs to be instantiated and in scope for a valid value to be displayed. This is much less powerful and more restrictive than using the Immediate Window.
Along with inspecting methods, you can do simple math equations:
? 5 * 6
30
or compare values:
? 5==6
false
? 6==6
true
The question mark ('?') is unnecessary if you are in directly in the Immediate Window but it is included here for clarity (to distinguish between the typed in expressions versus the results.) However, if you are in the Command Window and need to do some quick stuff in the Immediate Window then precede your statements with '?' and off you go.
Intellisense works in the Immediate Window, but it sometimes can be a bit inconsistent. In my experience, it seems to be only available in Debug mode, but not in design, non-debug mode.
Unfortunately, another drawback of the Immediate Window is that it does not support loops.
2 column div layout: right column with fixed width, left fluid
Remove the float on the left column.
At the HTML code, the right column needs to come before the left one.
If the right has a float (and a width), and if the left column doesn't have a width and no float, it will be flexible :)
Also apply an overflow: hidden
and some height (can be auto) to the outer div, so that it surrounds both inner divs.
Finally, at the left column, add a width: auto
and overflow: hidden
, this makes the left column independent from the right one (for example, if you resized the browser window, and the right column touched the left one, without these properties, the left column would run arround the right one, with this properties it remains in its space).
Example HTML:
<div class="container">
<div class="right">
right content fixed width
</div>
<div class="left">
left content flexible width
</div>
</div>
CSS:
.container {
height: auto;
overflow: hidden;
}
.right {
width: 180px;
float: right;
background: #aafed6;
}
.left {
float: none; /* not needed, just for clarification */
background: #e8f6fe;
/* the next props are meant to keep this block independent from the other floated one */
width: auto;
overflow: hidden;
}??
Example here: http://jsfiddle.net/jackJoe/fxWg7/
Delete the 'first' record from a table in SQL Server, without a WHERE condition
WITH q AS
(
SELECT TOP 1 *
FROM mytable
/* You may want to add ORDER BY here */
)
DELETE
FROM q
Note that
DELETE TOP (1)
FROM mytable
will also work, but, as stated in the documentation:
The rows referenced in the TOP
expression used with INSERT
, UPDATE
, or DELETE
are not arranged in any order.
Therefore, it's better to use WITH
and an ORDER BY
clause, which will let you specify more exactly which row you consider to be the first.
How do I resolve "Cannot find module" error using Node.js?
Just found an unusual scenario that may be of use to someone and is sort of a red herring.
I was also getting the Cannot Find Module error but oddly everything worked perfectly in my local (Mac hosted) Node.js environment. This problem only appeared when the code was deployed on our Linux server.
Well... it turned out to be a typo that (apparently) the Mac based Node.js installation was perfectly happy to ignore.
The include looked like this:
var S3Uploader = require('./S3Uploader.class');
But the actual file was called "s3Uploader.class.js"
Notice the casing difference in the 's' vs. 'S' between the code and the filename.
So - in the odd chance that none of the other solutions here are solving your problem, triple check that you're not mis-casing the characters in your included filename! :)
and DUH!
Unable to set default python version to python3 in ubuntu
As it says, update-alternatives --install
needs <link> <name> <path> and <priority> arguments.
You have link (/usr/bin/python
), name (python
), and path (/usr/bin/python3
), you're missing priority.
update-alternatives --help
says:
<priority> is an integer; options with higher numbers have higher priority in automatic mode.
So just put a 100
or something at the end
get the titles of all open windows
Based on the previous answer that give me some errors, finaly I use this code with GetOpenedWindows
function:
public class InfoWindow
{
public IntPtr Handle = IntPtr.Zero;
public FileInfo File = new FileInfo( Application.ExecutablePath );
public string Title = Application.ProductName;
public override string ToString() {
return File.Name + "\t>\t" + Title;
}
}//CLASS
/// <summary>Contains functionality to get info on the open windows.</summary>
public static class RuningWindows
{
internal static event EventHandler WindowActivatedChanged;
internal static Timer TimerWatcher = new Timer();
internal static InfoWindow WindowActive = new InfoWindow();
internal static void DoStartWatcher() {
TimerWatcher.Interval = 500;
TimerWatcher.Tick += TimerWatcher_Tick;
TimerWatcher.Start();
}
/// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
/// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
public static IDictionary<IntPtr , InfoWindow> GetOpenedWindows()
{
IntPtr shellWindow = GetShellWindow();
Dictionary<IntPtr , InfoWindow> windows = new Dictionary<IntPtr , InfoWindow>();
EnumWindows( new EnumWindowsProc( delegate( IntPtr hWnd , int lParam ) {
if ( hWnd == shellWindow ) return true;
if ( !IsWindowVisible( hWnd ) ) return true;
int length = GetWindowTextLength( hWnd );
if ( length == 0 ) return true;
StringBuilder builder = new StringBuilder( length );
GetWindowText( hWnd , builder , length + 1 );
var info = new InfoWindow();
info.Handle = hWnd;
info.File = new FileInfo( GetProcessPath( hWnd ) );
info.Title = builder.ToString();
windows[hWnd] = info;
return true;
} ) , 0 );
return windows;
}
private delegate bool EnumWindowsProc( IntPtr hWnd , int lParam );
public static string GetProcessPath( IntPtr hwnd )
{
uint pid = 0;
GetWindowThreadProcessId( hwnd , out pid );
if ( hwnd != IntPtr.Zero ) {
if ( pid != 0 ) {
var process = Process.GetProcessById( (int) pid );
if ( process != null ) {
return process.MainModule.FileName.ToString();
}
}
}
return "";
}
[DllImport( "USER32.DLL" )]
private static extern bool EnumWindows( EnumWindowsProc enumFunc , int lParam );
[DllImport( "USER32.DLL" )]
private static extern int GetWindowText( IntPtr hWnd , StringBuilder lpString , int nMaxCount );
[DllImport( "USER32.DLL" )]
private static extern int GetWindowTextLength( IntPtr hWnd );
[DllImport( "USER32.DLL" )]
private static extern bool IsWindowVisible( IntPtr hWnd );
[DllImport( "USER32.DLL" )]
private static extern IntPtr GetShellWindow();
[DllImport( "user32.dll" )]
private static extern IntPtr GetForegroundWindow();
//WARN: Only for "Any CPU":
[DllImport( "user32.dll" , CharSet = CharSet.Auto , SetLastError = true )]
private static extern int GetWindowThreadProcessId( IntPtr handle , out uint processId );
static void TimerWatcher_Tick( object sender , EventArgs e )
{
var windowActive = new InfoWindow();
windowActive.Handle = GetForegroundWindow();
string path = GetProcessPath( windowActive.Handle );
if ( string.IsNullOrEmpty( path ) ) return;
windowActive.File = new FileInfo( path );
int length = GetWindowTextLength( windowActive.Handle );
if ( length == 0 ) return;
StringBuilder builder = new StringBuilder( length );
GetWindowText( windowActive.Handle , builder , length + 1 );
windowActive.Title = builder.ToString();
if ( windowActive.ToString() != WindowActive.ToString() ) {
//fire:
WindowActive = windowActive;
if ( WindowActivatedChanged != null ) WindowActivatedChanged( sender , e );
Console.WriteLine( "Window: " + WindowActive.ToString() );
}
}
}//CLASS
Warning: You can only compil/debug under "Any CPU" to access to 32bits Apps...
Easy way to concatenate two byte arrays
Another possibility is using java.nio.ByteBuffer
.
Something like
ByteBuffer bb = ByteBuffer.allocate(a.length + b.length + c.length);
bb.put(a);
bb.put(b);
bb.put(c);
byte[] result = bb.array();
// or using method chaining:
byte[] result = ByteBuffer
.allocate(a.length + b.length + c.length)
.put(a).put(b).put(c)
.array();
Note that the array must be appropriately sized to start with, so the allocation line is required (as array()
simply returns the backing array, without taking the offset, position or limit into account).
What does this symbol mean in JavaScript?
See the documentation on MDN about expressions and operators and statements.
Basic keywords and general expressions
this
keyword:
var x = function()
vs. function x()
— Function declaration syntax
(function(){
…})()
— IIFE (Immediately Invoked Function Expression)
someFunction()()
— Functions which return other functions
=>
— Equal sign, greater than: arrow function expression syntax
|>
— Pipe, greater than: Pipeline operator
function*
, yield
, yield*
— Star after function
or yield
: generator functions
[]
, Array()
— Square brackets: array notation
If the square brackets appear on the left side of an assignment ([a] = ...
), or inside a function's parameters, it's a destructuring assignment.
{key: value}
— Curly brackets: object literal syntax (not to be confused with blocks)
If the curly brackets appear on the left side of an assignment ({ a } = ...
) or inside a function's parameters, it's a destructuring assignment.
`
…${
…}
…`
— Backticks, dollar sign with curly brackets: template literals
/
…/
— Slashes: regular expression literals
$
— Dollar sign in regex replace patterns: $$
, $&
, $`
, $'
, $n
()
— Parentheses: grouping operator
Property-related expressions
obj.prop
, obj[prop]
, obj["prop"]
— Square brackets or dot: property accessors
?.
, ?.[]
, ?.()
— Question mark, dot: optional chaining operator
::
— Double colon: bind operator
new
operator
...iter
— Three dots: spread syntax; rest parameters
Increment and decrement
++
, --
— Double plus or minus: pre- / post-increment / -decrement operators
Unary and binary (arithmetic, logical, bitwise) operators
delete
operator
void
operator
+
, -
— Plus and minus: addition or concatenation, and subtraction operators; unary sign operators
%
— Percent sign: remainder operator
&&
, ||
, !
— Double ampersand, double pipe, exclamation point: logical operators
??
— Double question mark: nullish-coalescing operator
**
— Double star: power operator (exponentiation)
Equality operators
==
, ===
— Equal signs: equality operators
!=
, !==
— Exclamation point and equal signs: inequality operators
Bit shift operators
<<
, >>
, >>>
— Two or three angle brackets: bit shift operators
Conditional operator
…?
…:
… — Question mark and colon: conditional (ternary) operator
=
— Equal sign: assignment operator
%=
— Percent equals: remainder assignment
+=
— Plus equals: addition assignment operator
&&=
, ||=
, ??=
— Double ampersand, pipe, or question mark, followed by equal sign: logical assignments
Destructuring
Comma operator
,
— Comma operator
Control flow
{
…}
— Curly brackets: blocks (not to be confused with object literal syntax)
Declarations
var
, let
, const
— Declaring variables
Label
label:
— Colon: labels
#
— Hash (number sign): Private methods or private fields
Convert InputStream to BufferedReader
A BufferedReader constructor takes a reader as argument, not an InputStream. You should first create a Reader from your stream, like so:
Reader reader = new InputStreamReader(is);
BufferedReader br = new BufferedReader(reader);
Preferrably, you also provide a Charset or character encoding name to the StreamReader constructor. Since a stream just provides bytes, converting these to text means the encoding must be known. If you don't specify it, the system default is assumed.
React component initialize state from props
It should be noted that it is an anti-pattern to copy properties that never change to the state (just access .props directly in that case). If you have a state variable that will change eventually but starts with a value from .props, you don't even need a constructor call - these local variables are initialized after a call to the parent's constructor:
class FirstComponent extends React.Component {
state = {
x: this.props.initialX,
// You can even call functions and class methods:
y: this.someMethod(this.props.initialY),
};
}
This is a shorthand equivalent to the answer from @joews below. It seems to only work on more recent versions of es6 transpilers, I have had issues with it on some webpack setups. If this doesn't work for you, you can try adding the babel plugin babel-plugin-transform-class-properties
, or you can use the non-shorthand version by @joews below.
Split a python list into other "sublists" i.e smaller lists
I'd say
chunks = [data[x:x+100] for x in range(0, len(data), 100)]
If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange()
, changing the above code to:
chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]
jQuery find parent form
I would suggest using closest
, which selects the closest matching parent element:
$('input[name="submitButton"]').closest("form");
Instead of filtering by the name, I would do this:
$('input[type=submit]').closest("form");
Convert generic List/Enumerable to DataTable?
If you are using VB.NET then this class does the job.
Imports System.Reflection
''' <summary>
''' Convert any List(Of T) to a DataTable with correct column types and converts Nullable Type values to DBNull
''' </summary>
Public Class ConvertListToDataset
Public Function ListToDataset(Of T)(ByVal list As IList(Of T)) As DataTable
Dim dt As New DataTable()
'/* Create the DataTable columns */
For Each pi As PropertyInfo In GetType(T).GetProperties()
If pi.PropertyType.IsValueType Then
Debug.Print(pi.Name)
End If
If IsNothing(Nullable.GetUnderlyingType(pi.PropertyType)) Then
dt.Columns.Add(pi.Name, pi.PropertyType)
Else
dt.Columns.Add(pi.Name, Nullable.GetUnderlyingType(pi.PropertyType))
End If
Next
'/* Populate the DataTable with the values in the Items in List */
For Each item As T In list
Dim dr As DataRow = dt.NewRow()
For Each pi As PropertyInfo In GetType(T).GetProperties()
dr(pi.Name) = IIf(IsNothing(pi.GetValue(item)), DBNull.Value, pi.GetValue(item))
Next
dt.Rows.Add(dr)
Next
Return dt
End Function
End Class
Google Maps API v3 adding an InfoWindow to each marker
Try this:
for (var i in tracks[racer_id].data.points) {
values = tracks[racer_id].data.points[i];
point = new google.maps.LatLng(values.lat, values.lng);
if (values.qst) {
var marker = new google.maps.Marker({map: map, position: point, clickable: true});
tracks[racer_id].markers[i] = marker;
var info = new google.maps.InfoWindow({
content: '<b>Speed:</b> ' + values.inst + ' knots'
});
tracks[racer_id].info[i] = info;
google.maps.event.addListener(tracks[racer_id].markers[i], 'click', function() {
tracks[racer_id].info[i].open(map, tracks[racer_id].markers[i]);
});
}
track_coordinates.push(point);
bd.extend(point);
}
Running a shell script through Cygwin on Windows
If you don't mind always including .sh on the script file name, then you can keep the same script for Cygwin and Unix (Macbook).
To illustrate:
1. Always include .sh to your script file name, e.g., test1.sh
2. test1.sh looks like the following as an example:
#!/bin/bash
echo '$0 = ' $0
echo '$1 = ' $1
filepath=$1
3. On Windows with Cygwin, you type "test1.sh" to run
4. On a Unix, you also type "test1.sh" to run
Note: On Windows, you need to use the file explorer to do following once:
1. Open the file explorer
2. Right-click on a file with .sh extension, like test1.sh
3. Open with... -> Select sh.exe
After this, your Windows 10 remembers to execute all .sh files with sh.exe.
Note: Using this method, you do not need to prepend your script file name with bash to run
Real time face detection OpenCV, Python
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
How to launch an Activity from another Application in Android
If you don't know the main activity, then the package name can be used to launch the application.
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.package.address");
if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
}
scp from Linux to Windows
If you want to copy paste files from Unix to Windows and Windows to Unix just use filezilla with port 22.
HTTP Content-Type Header and JSON
Recently ran into a problem with this and a Chrome extension that was corrupting a JSON stream when the response header labeled the content-type as 'text/html' apparently extensions can and will use the response header to alter the content prior to further processing by the browser. Changing the content-type fixed the issue.
Android Calling JavaScript functions in WebView
From kitkat onwards use evaluateJavascript method instead loadUrl to call the javascript functions like below
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("enable();", null);
} else {
webView.loadUrl("javascript:enable();");
}
Timeout jQuery effects
This can be done with only a few lines of jQuery:
$(function(){
// make sure img is hidden - fade in
$('img').hide().fadeIn(2000);
// after 5 second timeout - fade out
setTimeout(function(){$('img').fadeOut(2000);}, 5000);
});?
see the fiddle below for a working example...
How to pass the values from one jsp page to another jsp without submit button?
I dont exactly know what you want to do.But you cant send data of one form using a submit button of another form.
You could do one thing either use sessions or use hidden fields that has the submit button. You could use javascript/jquery to pass the values from the first form to the hidden fields of the second form.Then you could submit the form.
Or else the easiest you could do is use sessions.
<form>
<input type="text" class="input-text " value="" size="32" name="user_data[firstname]" id="elm_6">
<input type="text" class="input-text " value="" size="32" name="user_data[lastname]" id="elm_7">
</form>
<form action="#">
<input type="text" class="input-text " value="" size="32" name="user_data[b_firstname]" id="elm_14">
<input type="text" class="input-text " value="" size="32" name="user_data[s_firstname]" id="elm_16">
<input type="submit" value="Continue" name="dispatch[checkout.update_steps]">
</form>
$('input[type=submit]').click(function(){
$('#elm_14').val($('#elm_6').val());
$('#elm_16').val($('#elm_7').val());
});
This is the jsfiddle for it http://jsfiddle.net/FPsdy/102/
Checking Value of Radio Button Group via JavaScript?
Without loop:
document.getElementsByName('gender').reduce(function(value, checkable) {
if(checkable.checked == true)
value = checkable.value;
return value;
}, '');
reduce
is just a function that will feed sequentially array elements to second argument of callback, and previously returned function to value, while for the first run, it will use value of second argument.
The only minus of this approach is that reduce will traverse every element returned by getElementsByName
even after it have found selected radio button.
Find the directory part (minus the filename) of a full path in access 97
If you are confident in your input parameters, you can use this single line of code which uses the native Split and Join functions and Excel native Application.pathSeparator.
Split(Join(Split(strPath, "."), Application.pathSeparator), Application.pathSeparator)
If you want a more extensive function, the code below is tested in Windows and should also work on Mac (though not tested). Be sure to also copy the supporting function GetPathSeparator, or modify the code to use Application.pathSeparator. Note, this is a first draft; I should really refactor it to be more concise.
Private Sub ParsePath2Test()
'ParsePath2(DrivePathFileExt, -2) returns a multi-line string for debugging.
Dim p As String, n As Integer
Debug.Print String(2, vbCrLf)
If True Then
Debug.Print String(2, vbCrLf)
Debug.Print ParsePath2("", -2)
Debug.Print ParsePath2("C:", -2)
Debug.Print ParsePath2("C:\", -2)
Debug.Print ParsePath2("C:\Windows", -2)
Debug.Print ParsePath2("C:\Windows\notepad.exe", -2)
Debug.Print ParsePath2("C:\Windows\SysWOW64", -2)
Debug.Print ParsePath2("C:\Windows\SysWOW64\", -2)
Debug.Print ParsePath2("C:\Windows\SysWOW64\AcLayers.dll", -2)
Debug.Print ParsePath2("C:\Windows\SysWOW64\.fakedir", -2)
Debug.Print ParsePath2("C:\Windows\SysWOW64\fakefile.ext", -2)
End If
If True Then
Debug.Print String(1, vbCrLf)
Debug.Print ParsePath2("\Windows", -2)
Debug.Print ParsePath2("\Windows\notepad.exe", -2)
Debug.Print ParsePath2("\Windows\SysWOW64", -2)
Debug.Print ParsePath2("\Windows\SysWOW64\", -2)
Debug.Print ParsePath2("\Windows\SysWOW64\AcLayers.dll", -2)
Debug.Print ParsePath2("\Windows\SysWOW64\.fakedir", -2)
Debug.Print ParsePath2("\Windows\SysWOW64\fakefile.ext", -2)
End If
If True Then
Debug.Print String(1, vbCrLf)
Debug.Print ParsePath2("Windows\notepad.exe", -2)
Debug.Print ParsePath2("Windows\SysWOW64", -2)
Debug.Print ParsePath2("Windows\SysWOW64\", -2)
Debug.Print ParsePath2("Windows\SysWOW64\AcLayers.dll", -2)
Debug.Print ParsePath2("Windows\SysWOW64\.fakedir", -2)
Debug.Print ParsePath2("Windows\SysWOW64\fakefile.ext", -2)
Debug.Print ParsePath2(".fakedir", -2)
Debug.Print ParsePath2("fakefile.txt", -2)
Debug.Print ParsePath2("fakefile.onenote", -2)
Debug.Print ParsePath2("C:\Personal\Workspace\Code\PythonVenvs\xlwings_test\.idea", -2)
Debug.Print ParsePath2("Windows", -2) ' Expected to raise error 52
End If
If True Then
Debug.Print String(2, vbCrLf)
Debug.Print "ParsePath2 ""\Windows\SysWOW64\fakefile.ext"" with different ReturnType values"
Debug.Print , "{empty}", "D", ParsePath2("Windows\SysWOW64\fakefile.ext")(1)
Debug.Print , "0", "D", ParsePath2("Windows\SysWOW64\fakefile.ext", 0)(1)
Debug.Print , "1", "ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 1)
Debug.Print , "10", "file", ParsePath2("Windows\SysWOW64\fakefile.ext", 10)
Debug.Print , "11", "file.ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 11)
Debug.Print , "100", "path", ParsePath2("Windows\SysWOW64\fakefile.ext", 100)
Debug.Print , "110", "path\file", ParsePath2("Windows\SysWOW64\fakefile.ext", 110)
Debug.Print , "111", "path\file.ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 111)
Debug.Print , "1000", "D", ParsePath2("Windows\SysWOW64\fakefile.ext", 1000)
Debug.Print , "1100", "D:\path", ParsePath2("Windows\SysWOW64\fakefile.ext", 1100)
Debug.Print , "1110", "D:\p\file", ParsePath2("Windows\SysWOW64\fakefile.ext", 1110)
Debug.Print , "1111", "D:\p\f.ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 1111)
On Error GoTo EH:
' This is expected to presetn an error:
p = "Windows\SysWOW64\fakefile.ext"
n = 1010
Debug.Print "1010", "D:\p\file.ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 1010)
On Error GoTo 0
End If
Exit Sub
EH:
Debug.Print , CStr(n), "Error: "; Err.Number, Err.Description
Resume Next
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Function ParsePath2(ByVal DrivePathFileExt As String _
, Optional ReturnType As Integer = 0)
' Writen by Chris Advena. You may modify and use this code provided you leave
' this credit in the code.
' Parses the input DrivePathFileExt string into individual components (drive
' letter, folders, filename and extension) and returns the portions you wish
' based on ReturnType.
' Returns either an array of strings (ReturnType = 0) or an individual string
' (all other defined ReturnType values).
'
' Parameters:
' DrivePathFileExt: The full drive letter, path, filename and extension
' ReturnType: -2 or a string up of to 4 ones with leading or lagging zeros
' (e.g., 0001)
' -2: special code for debugging use in ParsePath2Test().
' Results in printing verbose information to the Immediate window.
' 0: default: Array(driveStr, pathStr, fileStr, extStr)
' 1: extension
' 10: filename stripped of extension
' 11: filename.extension, excluding drive and folders
' 100: folders, excluding drive letter filename and extension
' 111: folders\filename.extension, excluding drive letter
' 1000: drive leter only
' 1100: drive:\folders, excluding filename and extension
' 1110: drive:\folders\filename, excluding extension
' 1010, 0101, 1001: invalid ReturnTypes. Will result raise error 380, Value
' is not valid.
Dim driveStr As String, pathStr As String
Dim fileStr As String, extStr As String
Dim drivePathStr As String
Dim pathFileExtStr As String, fileExtStr As String
Dim s As String, cnt As Integer
Dim i As Integer, slashStr As String
Dim dotLoc As Integer, slashLoc As Integer, colonLoc As Integer
Dim extLen As Integer, fileLen As Integer, pathLen As Integer
Dim errStr As String
DrivePathFileExt = Trim(DrivePathFileExt)
If DrivePathFileExt = "" Then
fileStr = ""
extStr = ""
fileExtStr = ""
pathStr = ""
pathFileExtStr = ""
drivePathStr = ""
GoTo ReturnResults
End If
' Determine if Dos(/) or UNIX(\) slash is used
slashStr = GetPathSeparator(DrivePathFileExt)
' Find location of colon, rightmost slash and dot.
' COLON: colonLoc and driveStr
colonLoc = 0
driveStr = ""
If Mid(DrivePathFileExt, 2, 1) = ":" Then
colonLoc = 2
driveStr = Left(DrivePathFileExt, 1)
End If
#If Mac Then
pathFileExtStr = DrivePathFileExt
#Else ' Windows
pathFileExtStr = ""
If Len(DrivePathFileExt) > colonLoc _
Then pathFileExtStr = Mid(DrivePathFileExt, colonLoc + 1)
#End If
' SLASH: slashLoc, fileExtStr and fileStr
' Find the rightmost path separator (Win backslash or Mac Fwdslash).
slashLoc = InStrRev(DrivePathFileExt, slashStr, -1, vbBinaryCompare)
' DOT: dotLoc and extStr
' Find rightmost dot. If that dot is not part of a relative reference,
' then set dotLoc. dotLoc is meant to apply to the dot before an extension,
' NOT relative path reference dots. REl ref dots appear as "." or ".." at
' the very leftmost of the path string.
dotLoc = InStrRev(DrivePathFileExt, ".", -1, vbTextCompare)
If Left(DrivePathFileExt, 1) = "." And dotLoc <= 2 Then dotLoc = 0
If slashLoc + 1 = dotLoc Then
dotLoc = 0
If Len(extStr) = 0 And Right(pathFileExtStr, 1) <> slashStr _
Then pathFileExtStr = pathFileExtStr & slashStr
End If
#If Not Mac Then
' In windows, filenames cannot end with a dot (".").
If dotLoc = Len(DrivePathFileExt) Then
s = "Error in FileManagementMod.ParsePath2 function. " _
& "DrivePathFileExt " & DrivePathFileExt _
& " cannot end iwth a dot ('.')."
Err.Raise 52, "FileManagementMod.ParsePath2", s
End If
#End If
' extStr
extStr = ""
If dotLoc > 0 And (dotLoc < Len(DrivePathFileExt)) _
Then extStr = Mid(DrivePathFileExt, dotLoc + 1)
' fileExtStr
fileExtStr = ""
If slashLoc > 0 _
And slashLoc < Len(DrivePathFileExt) _
And dotLoc > slashLoc Then
fileExtStr = Mid(DrivePathFileExt, slashLoc + 1)
End If
' Validate the input: DrivePathFileExt
s = ""
#If Mac Then
If InStr(1, DrivePathFileExt, ":") > 0 Then
s = "DrivePathFileExt ('" & DrivePathFileExt _
& "')has invalid format. " _
& "UNIX/Mac filenames cannot contain a colon ('.')."
End If
#End If
If Not colonLoc = 0 And slashLoc = 0 And dotLoc = 0 _
And Left(DrivePathFileExt, 1) <> slashStr _
And Left(DrivePathFileExt, 1) <> "." Then
s = "DrivePathFileExt ('" & DrivePathFileExt _
& "') has invalid format. " _
& "Good example: 'C:\folder\file.txt'"
ElseIf colonLoc <> 0 And colonLoc <> 2 Then
' We are on Windows and there is a colon; it can only be
' in position 2.
s = "DrivePathFileExt ('" & DrivePathFileExt _
& "') has invalid format. " _
& "In the Windows operating system, " _
& "a colon (':') can only be the second character '" _
& "of a valid file path. "
ElseIf Left(DrivePathFileExt, 1) = ":" _
Or InStr(3, DrivePathFileExt, ":", vbTextCompare) > 0 Then
'If path contains a drive letter, it must contain at least one slash.
s = "DrivePathFileExt ('" & DrivePathFileExt _
& "') has invalid format. " _
& "Colon can only appear in the second character position." _
& slashStr & "')."
ElseIf colonLoc > 0 And slashLoc = 0 _
And Len(DrivePathFileExt) > 2 Then
'If path contains a drive letter, it must contain at least one slash.
s = "DrivePathFileExt ('" & DrivePathFileExt _
& "') has invalid format. " _
& "The last dot ('.') cannot be before the last file separator '" _
& slashStr & "')."
ElseIf colonLoc = 2 _
And InStr(1, DrivePathFileExt, slashStr, vbTextCompare) = 0 _
And Len(DrivePathFileExt) > 2 Then
' There is a colon, but no file separator (slash). This is invalid.
s = "DrivePathFileExt ('" & DrivePathFileExt _
& "') has invalid format. " _
& "If a drive letter is included, then there must be at " _
& "least one file separator character ('" & slashStr & "')."
ElseIf Len(driveStr) > 0 And Len(DrivePathFileExt) > 2 And slashLoc = 0 Then
' If path contains a drive letter and is more than 2 character long
' (e.g., 'C:'), it must contain at least one slash.
s = "DrivePathFileExt cannot contain a drive letter but no path separator."
End If
If Len(s) > 0 Then
End If
' Determine if DrivePathFileExt = DrivePath
' or = Path (with no fileStr or extStr components).
If Right(DrivePathFileExt, 1) = slashStr _
Or slashLoc = 0 _
Or dotLoc = 0 _
Or (dotLoc > 0 And dotLoc <= slashLoc + 1) Then
' If rightmost character is the slashStr, then no fileExt exists, just drivePath
' If no dot found, then no extension. Assume a folder is after the last slashstr,
' not a filename.
' If a dot is found (extension exists),
' If a rightmost dot appears one-char to the right of the rightmost slash
' or anywhere before (left) of that, it is not a file/ext separator. Exmaple:
' 'C:\folder1\.folder2' Then
' If no slashes, then no fileExt exists. It must just be a driveletter.
' DrivePathFileExt contains no file or ext name.
fileStr = ""
extStr = ""
fileExtStr = ""
pathStr = pathFileExtStr
drivePathStr = DrivePathFileExt
GoTo ReturnResults
Else
' fileStr
fileStr = ""
If slashLoc > 0 Then
If Len(extStr) = 0 Then
fileStr = fileExtStr
Else
' length of filename excluding dot and extension.
i = Len(fileExtStr) - Len(extStr) - 1
fileStr = Left(fileExtStr, i)
End If
Else
s = "Error in FileManagementMod.ParsePath2 function. " _
& "*** Unhandled scenario: find fileStr when slashLoc = 0. *** "
Err.Raise 52, "FileManagementMod.ParsePath2", s
End If
' pathStr
pathStr = ""
' length of pathFileExtStr excluding fileExt.
i = Len(pathFileExtStr) - Len(fileExtStr)
pathStr = Left(pathFileExtStr, i)
' drivePathStr
drivePathStr = ""
' length of DrivePathFileExt excluding dot and extension.
i = Len(DrivePathFileExt) - Len(fileExtStr)
drivePathStr = Left(DrivePathFileExt, i)
End If
ReturnResults:
' ReturnType uses a 4-digit binary code: dpfe = drive path file extension,
' where 1 = return in array and 0 = do not return in array
' -2, and 0 are special cases that do not follow the code.
' Note: pathstr is determined with the tailing slashstr
If Len(drivePathStr) > 0 And Right(drivePathStr, 1) <> slashStr _
Then drivePathStr = drivePathStr & slashStr
If Len(pathStr) > 0 And Right(pathStr, 1) <> slashStr _
Then pathStr = pathStr & slashStr
#If Not Mac Then
' Including this code add a slash to the beginnning where missing.
' the downside is that it would create an absolute path where a
' sub-path of the current folder is intended.
'If colonLoc = 0 Then
' If Len(drivePathStr) > 0 And Not IsIn(Left(drivePathStr, 1), slashStr, ".") _
Then drivePathStr = slashStr & drivePathStr
' If Len(pathStr) > 0 And Not IsIn(Left(pathStr, 1), slashStr, ".") _
Then pathStr = slashStr & pathStr
' If Len(pathFileExtStr) > 0 And Not IsIn(Left(pathFileExtStr, 1), slashStr, ".") _
Then pathFileExtStr = slashStr & pathFileExtStr
'End If
#End If
Select Case ReturnType
Case -2 ' used for ParsePath2Test() only.
ParsePath2 = "DrivePathFileExt " _
& CStr(Nz(DrivePathFileExt, "{empty string}")) _
& vbCrLf & " " _
& "-------------- -----------------------------------------" _
& vbCrLf & " " & "D:\Path\ " & drivePathStr _
& vbCrLf & " " & "\path[\file.ext] " & pathFileExtStr _
& vbCrLf & " " & "\path\ " & pathStr _
& vbCrLf & " " & "file.ext " & fileExtStr _
& vbCrLf & " " & "file " & fileStr _
& vbCrLf & " " & "ext " & extStr _
& vbCrLf & " " & "D " & driveStr _
& vbCrLf & vbCrLf
' My custom debug printer prints to Immediate winodw and log file.
' Dbg.Prnt 2, ParsePath2
Debug.Print ParsePath2
Case 1 '0001: ext
ParsePath2 = extStr
Case 10 '0010: file
ParsePath2 = fileStr
Case 11 '0011: file.ext
ParsePath2 = fileExtStr
Case 100 '0100: path
ParsePath2 = pathStr
Case 110 '0110: (path, file)
ParsePath2 = pathStr & fileStr
Case 111 '0111:
ParsePath2 = pathFileExtStr
Case 1000
ParsePath2 = driveStr
Case 1100
ParsePath2 = drivePathStr
Case 1110
ParsePath2 = drivePathStr & fileStr
Case 1111
ParsePath2 = DrivePathFileExt
Case 1010, 101, 1001
s = "Error in FileManagementMod.ParsePath2 function. " _
& "Value of Paramter (ReturnType = " _
& CStr(ReturnType) & ") is not valid."
Err.Raise 380, "FileManagementMod.ParsePath2", s
Case Else ' default: 0
ParsePath2 = Array(driveStr, pathStr, fileStr, extStr)
End Select
End Function
Supporting function GetPathSeparatorTest extends the native Application.pathSeparator (or bypasses when needed) to work on Mac and Win. It can also takes an optional path string and will try to determine the path separator used in the string (favoring the OS native path separator).
Private Sub GetPathSeparatorTest()
Dim s As String
Debug.Print "GetPathSeparator(s):"
Debug.Print "s not provided: ", GetPathSeparator
s = "C:\folder1\folder2\file.ext"
Debug.Print "s = "; s, GetPathSeparator(DrivePathFileExt:=s)
s = "C:/folder1/folder2/file.ext"
Debug.Print "s = "; s, GetPathSeparator(DrivePathFileExt:=s)
End Sub
Function GetPathSeparator(Optional DrivePathFileExt As String = "") As String
' by Chris Advena
' Finds the path separator from a string, DrivePathFileExt.
' If DrivePathFileExt is not provided, return the operating system path separator
' (Windows = backslash, Mac = forwardslash).
' Mac/Win compatible.
' Initialize
Dim retStr As String: retStr = ""
Dim OSSlash As String: OSSlash = ""
Dim OSOppositeSlash As String: OSOppositeSlash = ""
Dim PathFileExtSlash As String
GetPathSeparator = ""
retStr = ""
' Determine if OS expects fwd or back slash ("/" or "\").
On Error GoTo EH
OSSlash = Application.pathSeparator
If DrivePathFileExt = "" Then
' Input parameter DrivePathFileExt is empty, so use OS file separator.
retStr = OSSlash
Else
' Input parameter DrivePathFileExt provided. See if it contains / or \.
' Set OSOppositeSlash to the opposite slash the OS expects.
OSOppositeSlash = "\"
If OSSlash = "\" Then OSOppositeSlash = "/"
' If DrivePathFileExt does NOT contain OSSlash
' and DOES contain OSOppositeSlash, return OSOppositeSlash.
' Otherwise, assume OSSlash is correct.
retStr = OSSlash
If InStr(1, DrivePathFileExt, OSSlash, vbTextCompare) = 0 _
And InStr(1, DrivePathFileExt, OSOppositeSlash, vbTextCompare) > 0 Then
retStr = OSOppositeSlash
End If
End If
GetPathSeparator = retStr
Exit Function
EH:
' Application.PathSeparator property does not exist in Access,
' so get it the slightly less easy way.
#If Mac Then ' Application.PathSeparator doesn't seem to exist in Access...
OSSlash = "/"
#Else
OSSlash = "\"
#End If
Resume Next
End Function
Supporting function (actually commented out, so you can skip this if you don't plan to use it).
Sub IsInTest()
' IsIn2 is case insensitive
Dim StrToFind As String, arr As Variant
arr = Array("Me", "You", "Dog", "Boo")
StrToFind = "doG"
Debug.Print "Is '" & CStr(StrToFind) & "' in list (expect True): " _
, IsIn(StrToFind, "Me", "You", "Dog", "Boo")
StrToFind = "Porcupine"
Debug.Print "Is '" & CStr(StrToFind) & "' in list (expect False): " _
, IsIn(StrToFind, "Me", "You", "Dog", "Boo")
End Sub
Function IsIn(ByVal StrToFind, ParamArray StringArgs() As Variant) As Boolean
' StrToFind: the string to find in the list of StringArgs()
' StringArgs: 1-dimensional array containing string values.
' Built for Strings, but actually works with other data types.
Dim arr As Variant
arr = StringArgs
IsIn = Not IsError(Application.Match(StrToFind, arr, False))
End Function
How do I get java logging output to appear on a single line?
This is what I'm using.
public class VerySimpleFormatter extends Formatter {
private static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
@Override
public String format(final LogRecord record) {
return String.format(
"%1$s %2$-7s %3$s\n",
new SimpleDateFormat(PATTERN).format(
new Date(record.getMillis())),
record.getLevel().getName(), formatMessage(record));
}
}
You'll get something like...
2016-08-19T17:43:14.295+09:00 INFO Hey~
2016-08-19T17:43:16.068+09:00 SEVERE Seriously?
2016-08-19T17:43:16.068+09:00 WARNING I'm warning you!!!
How do I count unique visitors to my site?
for finding out that user is new or old , Get user IP .
create a table for IPs and their visits timestamp .
check IF IP does not exists OR time()-saved_timestamp > 60*60*24 (for 1 day) ,edit the IP's timestamp to time()
(means now) and increase your view one .
else , do nothing .
FYI : user IP is stored in $_SERVER['REMOTE_ADDR']
variable
Linux command to print directory structure in the form of a tree
Adding the below function in bashrc lets you run the command without any arguments which displays the current directory structure and when run with any path as argument, will display the directory structure of that path. This avoids the need to switch to a particular directory before running the command.
function tree() {
find ${1:-.} | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"
}
This works in gitbash too.
Source: Comment from @javasheriff here
Securing a password in a properties file
What about providing a custom N-Factor authentication mechanism?
Before combining available methods, let's assume we can perform the following:
1) Hard-code inside the Java program
2) Store in a .properties file
3) Ask user to type password from command line
4) Ask user to type password from a form
5) Ask user to load a password-file from command line or a form
6) Provide the password through network
7) many alternatives (eg Draw A Secret, Fingerprint, IP-specific, bla bla bla)
1st option: We could make things more complicated for an attacker by using obfuscation, but this is not considered a good countermeasure. A good coder can easily understand how it works if he/she can access the file. We could even export a per-user binary (or just the obfuscation part or key-part), so an attacker must have access to this user-specific file, not another distro.
Again, we should find a way to change passwords, eg by recompiling or using reflection to on-the-fly change class behavior.
2nd option: We can store the password in the .properties file in an encrypted format, so it's not directly visible from an attacker (just like jasypt does). If we need a password manager we'll need a master password too which again should be stored somewhere - inside a .class file, the keystore, kernel, another file or even in memory - all have their pros and cons.
But, now users will just edit the .properties file for password change.
3rd option: type the password when running from command line e.g. java -jar /myprogram.jar -p sdflhjkiweHIUHIU8976hyd
.
This doesn't require the password to be stored and will stay in memory. However, history
commands and OS logs, may be your worst enemy here.
To change passwords on-the-fly, you will need to implement some methods (eg listen for console inputs, RMI, sockets, REST bla bla bla), but the password will always stay in memory.
One can even temporarily decrypt it only when required -> then delete the decrypted, but always keep the encrypted password in memory. Unfortunately, the aforementioned method does not increase security against unauthorized in-memory access, because the person who achieves that, will probably have access to the algorithm, salt and any other secrets being used.
4th option: provide the password from a custom form, rather than the command line. This will circumvent the problem of logging exposure.
5th option: provide a file as a password stored previously on a another medium -> then hard delete file. This will again circumvent the problem of logging exposure, plus no typing is required that could be shoulder-surfing stolen. When a change is required, provide another file, then delete again.
6th option: again to avoid shoulder-surfing, one can implement an RMI method call, to provide the password (through an encrypted channel) from another device, eg via a mobile phone. However, you now need to protect your network channel and access to the other device.
I would choose a combination of the above methods to achieve maximum security so one would have to access the .class files, the property file, logs, network channel, shoulder surfing, man in the middle, other files bla bla bla. This can be easily implemented using a XOR operation between all sub_passwords to produce the actual password.
We can't be protected from unauthorized in-memory access though, this can only be achieved by using some access-restricted hardware (eg smartcards, HSMs, SGX), where everything is computed into them, without anyone, even the legitimate owner being able to access decryption keys or algorithms. Again, one can steal this hardware too, there are reported side-channel attacks that may help attackers in key extraction and in some cases you need to trust another party (eg with SGX you trust Intel). Of course, situation may worsen when secure-enclave cloning (de-assembling) will be possible, but I guess this will take some years to be practical.
Also, one may consider a key sharing solution where the full key is split between different servers. However, upon reconstruction, the full key can be stolen. The only way to mitigate the aforementioned issue is by secure multiparty computation.
We should always keep in mind that whatever the input method, we need to ensure we are not vulnerable from network sniffing (MITM attacks) and/or key-loggers.
json: cannot unmarshal object into Go value of type
You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.
Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.
Saving ssh key fails
If you're using Windows, the unix-style default path of ssh-keygen is at fault.
In Line 2 it says Enter file in which to save the key (/c/Users/Eva/.ssh/id_rsa):
.
That full filename in the parantheses is the default, obviously Windows cannot access a file like that. If you type the Windows equivalent (c:\Users\Eva\.ssh\id_rsa
), it should work.
Before running this, you also need to create the folder. You can do this by running mkdir c:\Users\Eva\.ssh
, or by created the folder ".ssh." from File Explorer (note the second dot at the end, which will get removed automatically, and is required to create a folder that has a dot at the beginning).
c:\Users\Administrator\.ssh>ssh-keygen -t rsa -C "[email protected]"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/Administrator/.ssh/id_rsa): C:\Users\Administrator\.ssh\id_rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in C:\Users\Administrator\.ssh\id_rsa.
Your public key has been saved in C:\Users\Administrator\.ssh\id_rsa.pub.
The key fingerprint is:
... [email protected]
The key's randomart image is:...`
I know this is an old thread, but I thought the answer might help others.
PHP: HTML: send HTML select option attribute in POST
just combine the value and the stud_name e.g. 1_sre and split the value when get it into php. Javascript seems like hammer to crack a nut. N.B. this method assumes you can edit the the html. Here is what the html might look like:
<form name='add'>
Age: <select name='age'>
<option value='1_sre'>23</option>
<option value='2_sam>24</option>
<option value='5_john>25</option>
</select>
<input type='submit' name='submit'/>
</form>
How to convert string to float?
Unfortunately, there is no way to do this easily. Every solution has its drawbacks.
Use atof()
or strtof()
directly: this is what most people will tell you to do and it will work most of the time. However, if the program sets a locale or it uses a library that sets the locale (for instance, a graphics library that displays localised menus) and the user has their locale set to a language where the decimal separator is not .
(such as fr_FR
where the separator is ,
) these functions will stop parsing at the .
and you will stil get 4.0
.
Use atof()
or strtof()
but change the locale; it's a matter of calling setlocale(LC_ALL|~LC_NUMERIC, "");
before any call to atof()
or the likes. The problem with setlocale
is that it will be global to the process and you might interfer with the rest of the program. Note that you might query the current locale with setlocale()
and restore it after you're done.
Write your own float parsing routine. This might be quite quick if you do not need advanced features such as exponent parsing or hexadecimal floats.
Also, note that the value 4.08
cannot be represented exactly as a float; the actual value you will get is 4.0799999237060546875
.
How do I iterate through each element in an n-dimensional matrix in MATLAB?
One other trick is to use ind2sub
and sub2ind
. In conjunction with numel
and size
, this can let you do stuff like the following, which creates an N-dimensional array, and then sets all the elements on the "diagonal" to be 1.
d = zeros( 3, 4, 5, 6 ); % Let's pretend this is a user input
nel = numel( d );
sz = size( d );
szargs = cell( 1, ndims( d ) ); % We'll use this with ind2sub in the loop
for ii=1:nel
[ szargs{:} ] = ind2sub( sz, ii ); % Convert linear index back to subscripts
if all( [szargs{2:end}] == szargs{1} ) % On the diagonal?
d( ii ) = 1;
end
end
stdcall and cdecl
Raymond Chen gives a nice overview of what __stdcall
and __cdecl
does.
(1) The caller "knows" to clean up the stack after calling a function because the compiler knows the calling convention of that function and generates the necessary code.
void __stdcall StdcallFunc() {}
void __cdecl CdeclFunc()
{
// The compiler knows that StdcallFunc() uses the __stdcall
// convention at this point, so it generates the proper binary
// for stack cleanup.
StdcallFunc();
}
It is possible to mismatch the calling convention, like this:
LRESULT MyWndProc(HWND hwnd, UINT msg,
WPARAM wParam, LPARAM lParam);
// ...
// Compiler usually complains but there's this cast here...
windowClass.lpfnWndProc = reinterpret_cast<WNDPROC>(&MyWndProc);
So many code samples get this wrong it's not even funny. It's supposed to be like this:
// CALLBACK is #define'd as __stdcall
LRESULT CALLBACK MyWndProc(HWND hwnd, UINT msg
WPARAM wParam, LPARAM lParam);
// ...
windowClass.lpfnWndProc = &MyWndProc;
However, assuming the programmer doesn't ignore compiler errors, the compiler will generate the code needed to clean up the stack properly since it'll know the calling conventions of the functions involved.
(2) Both ways should work. In fact, this happens quite frequently at least in code that interacts with the Windows API, because __cdecl
is the default for C and C++ programs according to the Visual C++ compiler and the WinAPI functions use the __stdcall
convention.
(3) There should be no real performance difference between the two.
Eclipse - Failed to create the java virtual machine
I deleted my eclipse.ini after non of the above worked for me.
I fully expected the next run (when it looked likely to work) to recreate it so I could compare but it did not.
So I can't tell what fixed it specifically.
an oddity I did have however was jdk 1.7 but when I ran
C:\Users\jonathan.hardcastle>java -version
Registry key 'Software\JavaSoft\Java Runtime Environment\CurrentVersion'
has value '1.7', but '1.6' is required.
Error: could not find java.dll
Error: could not find Java SE Runtime Environment.
i got the above.. so I (re?)installed jre 1.7 specifically and that went away.
This was not linked to my eclipse success directly.
How to implement WiX installer upgrade?
The following is the sort of syntax I use for major upgrades:
<Product Id="*" UpgradeCode="PUT-GUID-HERE" Version="$(var.ProductVersion)">
<Upgrade Id="PUT-GUID-HERE">
<UpgradeVersion OnlyDetect="yes" Minimum="$(var.ProductVersion)" Property="NEWERVERSIONDETECTED" IncludeMinimum="no" />
<UpgradeVersion OnlyDetect="no" Maximum="$(var.ProductVersion)" Property="OLDERVERSIONBEINGUPGRADED" IncludeMaximum="no" />
</Upgrade>
<InstallExecuteSequence>
<RemoveExistingProducts After="InstallInitialize" />
</InstallExecuteSequence>
As @Brian Gillespie noted there are other places to schedule the RemoveExistingProducts depending on desired optimizations. Note the PUT-GUID-HERE must be identical.
How can I write variables inside the tasks file in ansible
Whenever you have a module followed by a variable on the same line in ansible the parser will treat the reference variable as the beginning of an in-line dictionary. For example:
- name: some example
command: {{ myapp }} -a foo
The default here is to parse the first part of {{ myapp }} -a foo
as a dictionary instead of a string and you will get an error.
So you must quote the argument like so:
- name: some example
command: "{{ myapp }} -a foo"
Corrupt jar file
This will happen when you doubleclick a JAR file in Windows explorer, but the JAR is by itself actually not an executable JAR. A real executable JAR should have at least a class with a main()
method and have it referenced in MANIFEST.MF
.
In Eclispe, you need to export the project as Runnable JAR file instead of as JAR file to get a real executable JAR.
Or, if your JAR is solely a container of a bunch of closely related classes (a library), then you shouldn't doubleclick it, but open it using some ZIP tool. Windows explorer namely by default associates JAR files with java.exe
, which won't work for those kind of libary JARs.
Does it matter what extension is used for SQLite database files?
In distributable software, I dont want my customers mucking about in the database by themselves. The program reads and writes it all by itself. The only reason for a user to touch the DB file is to take a backup copy. Therefore I have named it whatever_records.db
The simple .db extension tells the user that it is a binary data file and that's all they have to know. Calling it .sqlite invites the interested user to open it up and mess something up!
Totally depends on your usage scenario I suppose.
How to set image button backgroundimage for different state?
you can create selector file in res/drawable
example:
res/drawable/selector_button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_disabled" android:state_enabled="false" />
<item android:drawable="@drawable/btn_enabled" />
</selector>
and in layout activity, fragment or etc
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/selector_bg_rectangle_black"/>
How to check for null/empty/whitespace values with a single test?
Every single persons suggestion to run a query in Oracle to find records whose specific field is just blank, (this is not including (null) or any other field just a blank line) did not work. I tried every single suggested code. Guess I will keep searching online.
*****UPDATE*****
I tried this and it worked, not sure why it would not work if < 1 but for some reason < 2 worked and only returned records whose field is just blank
select [columnName] from [tableName] where LENGTH(columnName) < 2 ;
I am guessing whatever script that was used to convert data over has left something in the field even though it shows blank, that is my guess anyways as to why the < 2 works but not < 1
However, if you have any other values in that column field that is less than two characters then you might have to come up with another solution. If there are not a lot of other characters then you can single them out.
Hope my solution helps someone else out there some day.
Add one day to date in javascript
var datatoday = new Date();
var datatodays = datatoday.setDate(new Date(datatoday).getDate() + 1);
todate = new Date(datatodays);
console.log(todate);
This will help you...
How do I return JSON without using a template in Django?
Here's an example I needed for conditionally rendering json or html depending on the Request's Accept
header
# myapp/views.py
from django.core import serializers
from django.http import HttpResponse
from django.shortcuts import render
from .models import Event
def event_index(request):
event_list = Event.objects.all()
if request.META['HTTP_ACCEPT'] == 'application/json':
response = serializers.serialize('json', event_list)
return HttpResponse(response, content_type='application/json')
else:
context = {'event_list': event_list}
return render(request, 'polls/event_list.html', context)
you can test this with curl or httpie
$ http localhost:8000/event/
$ http localhost:8000/event/ Accept:application/json
note I opted not to use JsonReponse
as that would reserialize the model unnecessarily.
warning about too many open figures
import matplotlib.pyplot as plt
plt.rcParams.update({'figure.max_open_warning': 0})
If you use this, you won’t get that error, and it is the simplest way to do that.
What is callback in Android?
You create an interface first, then define a method, which would act as a callback. In this example we would have two classes, one classA and another classB
Interface:
public interface OnCustomEventListener{
public void onEvent(); //method, which can have parameters
}
the listener itself in classB (we only set the listener in classB)
private OnCustomEventListener mListener; //listener field
//setting the listener
public void setCustomEventListener(OnCustomEventListener eventListener) {
this.mListener=eventListener;
}
in classA, how we start listening for whatever classB has to tell
classB.setCustomEventListener(new OnCustomEventListener(){
public void onEvent(){
//do whatever you want to do when the event is performed.
}
});
how do we trigger an event from classB (for example on button pressed)
if(this.mListener!=null){
this.mListener.onEvent();
}
P.S. Your custom listener may have as many parameters as you want
Source
How do I set the colour of a label (coloured text) in Java?
For single color foreground color
label.setForeground(Color.RED)
For multiple foreground colors in the same label:
(I would probably put two labels next to each other using a GridLayout
or something, but here goes...)
You could use html in your label text as follows:
frame.add(new JLabel("<html>Text color: <font color='red'>red</font></html>"));
which produces:
What is the difference between .yaml and .yml extension?
As @David Heffeman indicates the recommendation is to use .yaml
when possible, and the recommendation has been that way since September 2006.
That some projects use .yml
is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).
The best way to approach this is to be rigorous when creating new files (i.e. use .yaml
) and be permissive when accepting input (i.e. allow .yml
when you encounter it), possible automatically upgrading/correcting these errors when possible.
The other recommendation I have is to document the argument(s) why you have to use .yml
, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml
has more pages than .yaml
" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml
extension instead of the correct .yaml
, but I think you will be hard pressed to do so.
Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose
used .yml
, but in later versions started to use .yaml
, although they still support .yml
). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml
instead of appveyor.yml
for building the windows wheels of my YAML parser for Python).
On the other hand:
The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.
So it seems fitting that they also use a subset of the recommended extension.