Decompile an APK, modify it and then recompile it
I know this question has been answered and I am not trying to give better answer here. I'll just share my experience in this topic.
Once I lost my code and I had the apk
file only. I decompiled it using the tool below and it made my day.
These tools MUST be used in such situation, otherwise, it is unethical and even sometimes it is illegal, (stealing somebody else's effort). So please use it wisely.
Those are my favorite tools for doing that:
javadecompilers.com
and to get the apk from google play you can google it or check out those sites:
On the date of posting this answer I tested all the links and it worked perfect for me.
NOTE: Apk Decompiling is not effective in case of proguarded code. Because Proguard shrink and obfuscates the code and rename classes to nonsense names which make it fairly hard to understand the code.
Bonus:
Basic tutorial of Using Proguard:
How to change already compiled .class file without decompile?
You can follow these steps to modify your java class:
- Decompile the .class file as you have done and save it as .java
- Create a project in Eclipse with that java file, the original JAR
as library, and all its dependencies
- Change the .java and compile
- Get the modified .class file and put it again inside the original
JAR.
How do you decompile a swf file
Get the Sothink SWF decompiler. Not free, but worth it. Recently used it to decompile an SWF that I had lost the fla for, and I could completely round-trip swf-fla and back!
link text
Is there a C++ decompiler?
information is discarded in the compiling process. Even if a decompiler could produce the logical equivalent code with classes and everything (it probably can't), the self-documenting part is gone in optimized release code. No variable names, no routine names, no class names - just addresses.
Is there a program to decompile Delphi?
I don't think there are any machine code decompilers that produce Pascal code. Most "Delphi decompilers" parse form and RTTI data, but do not actually decompile the machine code. I can only recommend using something like DeDe (or similar software) to extract symbol information in combination with a C decompiler, then translate the decompiled C code to Delphi (there are many source code converters out there).
Reverse engineering from an APK file to a project
Not really. There are a number of dex disassembler/decompiler suites out there such as smali, or dex2jar that will generate semi-humanreadable output (in the case of dex2jar, you can get java code through the use of something like JD-GUI but the process is not perfect and it is very unlikely that you'll be able to 100% recreate your source code. However, it could potentially give you a place to start rebuilding your source tree.
How can I protect my .NET assemblies from decompilation?
If you want to fully protect your app from decompilation, look at Aladdin's Hasp. You can wrap your assemblies in an encrypted shell that can only be accessed by your application. Of course one wonders how they're able to do this but it works. I don't know however if they protect your app from runtime attachment/reflection which is what Crack.NET is able to do.
-- Edit
Also be careful of compiling to native code as a solution...there are decompilers for native code as well.
Is there a Visual Basic 6 decompiler?
In my own experience where I needed to try and find out what some old VB6 programs were doing, I turned to Process Explorer (Sysinternals). I did the following:
- Run Process Explorer
- Run VB6 .exe
- Locate exe in Process Explorer
- Right click on process
- Check the "Strings" tab
This didn't show the actual functions, but it listed their names, folders of where files were being copied from and to and if it accessed a DB it would also display the connection string. Enough to help you get an idea, but may be useless for complex programs. The programs I was looking at were pretty basic (no pun intended).
YMMV.
Extract source code from .jar file
I know it's an old question Still thought it would help someone
1) Go to your jar file's folder.
2) change it's extension to .zip.
3) You are good to go and can easily extract it by just double clicking it.
Note: I tested this in MAC, it works. Hopefully it will work on windows too.
Is there a way to get the source code from an APK file?
I'll show you other way to decompile the .apk files.
You can follow the first 2 steps from "prankul garg". So you have another opportunities:
Step 3':
Download the "JD-GUI", thats easy to found this one.
Open your .jar file in "jd-gui.exe". (File > Open file > 'found your .jar file'). After this procedure, you can save all resources in a .zip file.
So,
1st - You have to rename the .apk file to .zip
2nd - You have to decode .dex file (if you want, decode the .apk file to dex2jar, that's possible)
3rd - You have to decode .jar file with JD-GUI
javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)
In our case we were getting UnmarshalException because a wrong Java package was specified in the following. The issue was resolved once the right package was in place:
@Bean
public Unmarshaller tmsUnmarshaller() {
final Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller
.setPackagesToScan("java.package.to.generated.java.classes.for.xsd");
return jaxb2Marshaller;
}
How do I clone a range of array elements to a new array?
How about useing Array.ConstrainedCopy:
int[] ArrayOne = new int[8] {1,2,3,4,5,6,7,8};
int[] ArrayTwo = new int[5];
Array.ConstrainedCopy(ArrayOne, 3, ArrayTwo, 0, 7-3);
Below is my original post. It will not work
You could use Array.CopyTo:
int[] ArrayOne = new int[8] {1,2,3,4,5,6,7,8};
int[] ArrayTwo = new int[5];
ArrayOne.CopyTo(ArrayTwo,3); //starts copy at index=3 until it reaches end of
//either array
Laravel Eloquent inner join with multiple conditions
You can see the following code to solved the problem
return $query->join('kg_shops', function($join)
{
$join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
$join->where('kg_shops.active','=', 1);
});
Or another way to solved it
return $query->join('kg_shops', function($join)
{
$join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
$join->on('kg_shops.active','=', DB::raw('1'));
});
How to get HTTP response code for a URL in Java?
HttpURLConnection:
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
This is by no means a robust example; you'll need to handle IOException
s and whatnot. But it should get you started.
If you need something with more capability, check out HttpClient.
How do I write to a Python subprocess' stdin?
To clarify some points:
As jro has mentioned, the right way is to use subprocess.communicate
.
Yet, when feeding the stdin
using subprocess.communicate
with input
, you need to initiate the subprocess with stdin=subprocess.PIPE
according to the docs.
Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.
Also qed has mentioned in the comments that for Python 3.4 you need to encode the string, meaning you need to pass Bytes to the input
rather than a string
. This is not entirely true. According to the docs, if the streams were opened in text mode, the input should be a string (source is the same page).
If streams were opened in text mode, input must be a string. Otherwise, it must be bytes.
So, if the streams were not opened explicitly in text mode, then something like below should work:
import subprocess
command = ['myapp', '--arg1', 'value_for_arg1']
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate(input='some data'.encode())[0]
I've left the stderr
value above deliberately as STDOUT
as an example.
That being said, sometimes you might want the output of another process rather than building it up from scratch. Let's say you want to run the equivalent of echo -n 'CATCH\nme' | grep -i catch | wc -m
. This should normally return the number characters in 'CATCH' plus a newline character, which results in 6. The point of the echo here is to feed the CATCH\nme
data to grep. So we can feed the data to grep with stdin in the Python subprocess chain as a variable, and then pass the stdout as a PIPE to the wc
process' stdin (in the meantime, get rid of the extra newline character):
import subprocess
what_to_catch = 'catch'
what_to_feed = 'CATCH\nme'
# We create the first subprocess, note that we need stdin=PIPE and stdout=PIPE
p1 = subprocess.Popen(['grep', '-i', what_to_catch], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# We immediately run the first subprocess and get the result
# Note that we encode the data, otherwise we'd get a TypeError
p1_out = p1.communicate(input=what_to_feed.encode())[0]
# Well the result includes an '\n' at the end,
# if we want to get rid of it in a VERY hacky way
p1_out = p1_out.decode().strip().encode()
# We create the second subprocess, note that we need stdin=PIPE
p2 = subprocess.Popen(['wc', '-m'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# We run the second subprocess feeding it with the first subprocess' output.
# We decode the output to convert to a string
# We still have a '\n', so we strip that out
output = p2.communicate(input=p1_out)[0].decode().strip()
This is somewhat different than the response here, where you pipe two processes directly without adding data directly in Python.
Hope that helps someone out.
How to handle change text of span
Found the solution here
Lets say you have span1 as <span id='span1'>my text</span>
text change events can be captured with:
$(document).ready(function(){
$("#span1").on('DOMSubtreeModified',function(){
// text change handler
});
});
SQLite DateTime comparison
My query I did as follows:
SELECT COUNT(carSold)
FROM cars_sales_tbl
WHERE date
BETWEEN '2015-04-01' AND '2015-04-30'
AND carType = "Hybrid"
I got the hint by @ifredy's answer. The all I did is, I wanted this query to be run in iOS, using Objective-C. And it works!
Hope someone who does iOS Development, will get use out of this answer too!
What is the difference between HTML tags <div> and <span>?
There are already good, detailed answers here, but no visual examples, so here's a quick illustration:
_x000D_
_x000D_
<div>This is a div.</div>_x000D_
<div>This is a div.</div>_x000D_
<div>This is a div.</div>_x000D_
<span>This is a span.</span>_x000D_
<span>This is a span.</span>_x000D_
<span>This is a span.</span>
_x000D_
_x000D_
_x000D_
<div>
is a block tag, while <span>
is an inline tag.
How to consume a webApi from asp.net Web API to store result in database?
public class EmployeeApiController : ApiController
{
private readonly IEmployee _employeeRepositary;
public EmployeeApiController()
{
_employeeRepositary = new EmployeeRepositary();
}
public async Task<HttpResponseMessage> Create(EmployeeModel Employee)
{
var returnStatus = await _employeeRepositary.Create(Employee);
return Request.CreateResponse(HttpStatusCode.OK, returnStatus);
}
}
Persistance
public async Task<ResponseStatusViewModel> Create(EmployeeModel Employee)
{
var responseStatusViewModel = new ResponseStatusViewModel();
var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
var command = new SqlCommand("usp_CreateEmployee", connection);
command.CommandType = CommandType.StoredProcedure;
var pEmployeeName = new SqlParameter("@EmployeeName", SqlDbType.VarChar, 50);
pEmployeeName.Value = Employee.EmployeeName;
command.Parameters.Add(pEmployeeName);
try
{
await connection.OpenAsync();
await command.ExecuteNonQueryAsync();
command.Dispose();
connection.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return responseStatusViewModel;
}
Repository
Task<ResponseStatusViewModel> Create(EmployeeModel Employee);
public class EmployeeConfig
{
public static string EmployeeConnectionString;
private const string EmployeeConnectionStringKey = "EmployeeConnectionString";
public static void InitializeConfig()
{
EmployeeConnectionString = GetConnectionStringValue(EmployeeConnectionStringKey);
}
private static string GetConnectionStringValue(string connectionStringName)
{
return Convert.ToString(ConfigurationManager.ConnectionStrings[connectionStringName]);
}
}
Java Thread Example?
Here is a simple example:
ThreadTest.java
public class ThreadTest
{
public static void main(String [] args)
{
MyThread t1 = new MyThread(0, 3, 300);
MyThread t2 = new MyThread(1, 3, 300);
MyThread t3 = new MyThread(2, 3, 300);
t1.start();
t2.start();
t3.start();
}
}
MyThread.java
public class MyThread extends Thread
{
private int startIdx, nThreads, maxIdx;
public MyThread(int s, int n, int m)
{
this.startIdx = s;
this.nThreads = n;
this.maxIdx = m;
}
@Override
public void run()
{
for(int i = this.startIdx; i < this.maxIdx; i += this.nThreads)
{
System.out.println("[ID " + this.getId() + "] " + i);
}
}
}
And some output:
[ID 9] 1
[ID 10] 2
[ID 8] 0
[ID 10] 5
[ID 9] 4
[ID 10] 8
[ID 8] 3
[ID 10] 11
[ID 10] 14
[ID 10] 17
[ID 10] 20
[ID 10] 23
An explanation - Each MyThread
object tries to print numbers from 0 to 300, but they are only responsible for certain regions of that range. I chose to split it by indices, with each thread jumping ahead by the number of threads total. So t1
does index 0, 3, 6, 9, etc.
Now, without IO, trivial calculations like this can still look like threads are executing sequentially, which is why I just showed the first part of the output. On my computer, after this output thread with ID 10 finishes all at once, followed by 9, then 8. If you put in a wait or a yield, you can see it better:
MyThread.java
System.out.println("[ID " + this.getId() + "] " + i);
Thread.yield();
And the output:
[ID 8] 0
[ID 9] 1
[ID 10] 2
[ID 8] 3
[ID 9] 4
[ID 8] 6
[ID 10] 5
[ID 9] 7
Now you can see each thread executing, giving up control early, and the next executing.
How to present a modal atop the current view in Swift
The only way I able to get this to work was by doing this on the presenting view controller:
func didTapButton() {
self.definesPresentationContext = true
self.modalTransitionStyle = .crossDissolve
let yourVC = self.storyboard?.instantiateViewController(withIdentifier: "YourViewController") as! YourViewController
let navController = UINavigationController(rootViewController: yourVC)
navController.modalPresentationStyle = .overCurrentContext
navController.modalTransitionStyle = .crossDissolve
self.present(navController, animated: true, completion: nil)
}
Bulk Insert to Oracle using .NET
The solution of Rob Stevenson-Legget is slow because he doesn't bind his values but he uses string.Format( ).
When you ask Oracle to execute a sql statement it starts with calculating the has value of this statement. After that it looks in a hash table whether it already knows this statement. If it already knows it statement it can retrieve its execution path from this hash table and execute this statement really fast because Oracle has executed this statement before. This is called the library cache and it doesn't work properly if you don't bind your sql statements.
For example don't do:
int n;
for (n = 0; n < 100000; n ++)
{
mycommand.CommandText = String.Format("INSERT INTO [MyTable] ([MyId]) VALUES({0})", n + 1);
mycommand.ExecuteNonQuery();
}
but do:
OracleParameter myparam = new OracleParameter();
int n;
mycommand.CommandText = "INSERT INTO [MyTable] ([MyId]) VALUES(?)";
mycommand.Parameters.Add(myparam);
for (n = 0; n < 100000; n ++)
{
myparam.Value = n + 1;
mycommand.ExecuteNonQuery();
}
Not using parameters can also cause sql injection.
Python concatenate text files
def concatFiles():
path = 'input/'
files = os.listdir(path)
for idx, infile in enumerate(files):
print ("File #" + str(idx) + " " + infile)
concat = ''.join([open(path + f).read() for f in files])
with open("output_concatFile.txt", "w") as fo:
fo.write(path + concat)
if __name__ == "__main__":
concatFiles()
Azure SQL Database "DTU percentage" metric
DTU is nothing but a blend of CPU, memory and IO. Why do we need a blend when these 3 are pretty clear? Because we want a unit for power. But it is still confusing in many ways.
eg: If I simply increase memory will it increase power(DTU)? If yes, how can DTU be a blend? It is a yes. In this memory-increase case, as per the query in the answer given by jyong, DTU will be equivalent to memory(since we increased it). MS has even a pricing model based on this DTU and it raised many questions.
Because of these confusions and questions, MS wanted to bring in another option.
We already had some specs in on-premise, why can't we use them? As a result, 'vCore pricing model' was born. In this model we have visibility to RAM and CPU. But not in DTU model.
The counter argument from DTU would be that DTU measures are calibrated using a benchmark that simulates real-world database workload. And that we are not in on-premise anymore ;). Yes it is designed with cloud computing in mind(but is also used in OLTP workloads).
But that is not all. Now that we are entering the pricing model the equation changes. The question now is about money and the bundle(what all features are included). Here DTU has some advantages(the way I see it) but enterprises with many existing licenses would disagree.
- DTU has one pricing(Compute + Storage + Backup). Simpler and can
start with lower pricing.
- vCore has different pricing (Compute, Storage). Software assurance
is available here. Enterprises will have on-premise licenses, this can be easily ported here(so they get big machines for less price than DTU model). Plus they commit for multiple years and get additional discounts.
We can switch between both when needed so if not sure start with DTU(Basic/Standard/Premium).
How can we know which pricing tier to use? Go to configure menu as given below: (on the right/left you can switch between both)
Even though Vcore is bigger 'machine' and for bigger things, the cost can sometimes be cheaper for enterprise organizations. Here is a proof. DTU costs $147 . But Vcore costs $111. That is because you can commit for 3 years(but still pay monthly) and also because of the license re-use option(enterprises will have on-premise licenses).
It is a bit too much than answering direct question but I am gonna go ahead and make this complete by answering 'how to choose between different options in DTU let alone choosing between DTU and vCore'. This is answered in this beautiful blog and this flowchart explains it all
How to kill/stop a long SQL query immediately?
This is kind of a silly answer, but it works reliably at least in my case:
In management studio, when the "Cancel Executing Query" doesn't stop the query I just click to close the current sql document. it asks me if I want to cancel the query, I say yes, and lo and behold in a few seconds it stops executing. After that it asks me if I want to save the document before closing. At this point I can click Cancel to keep the document open and continue working. No idea what's going on behind the scenes, but it seems to work.
javascript find and remove object in array based on key value
sift
is a powerful collection filter for operations like this and much more advanced ones. It works client side in the browser or server side in node.js.
var collection = [
{"id":"88","name":"Lets go testing"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"}
];
var sifted = sift({id: {$not: 88}}, collection);
It supports filters like $in
, $nin
, $exists
, $gte
, $gt
, $lte
, $lt
, $eq
, $ne
, $mod
, $all
, $and
, $or
, $nor
, $not
, $size
, $type
, and $regex
, and strives to be API-compatible with MongoDB collection filtering.
Set Memory Limit in htaccess
In your .htaccess you can add:
PHP 5.x
<IfModule mod_php5.c>
php_value memory_limit 64M
</IfModule>
PHP 7.x
<IfModule mod_php7.c>
php_value memory_limit 64M
</IfModule>
If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.
If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.
Read more on http://support.tigertech.net/php-value
How to read from a text file using VBScript?
Use first the method OpenTextFile
, and then...
either read the file at once with the method ReadAll
:
Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll
or line by line with the method ReadLine
:
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
'Loop over it
For Each line in dict.Items
WScript.Echo line
Next
How to compare strings in C conditional preprocessor-directives
The answere by Patrick and by Jesse Chisholm made me do the following:
#define QUEEN 'Q'
#define JACK 'J'
#define CHECK_QUEEN(s) (s==QUEEN)
#define CHECK_JACK(s) (s==JACK)
#define USER 'Q'
[... later on in code ...]
#if CHECK_QUEEN(USER)
compile_queen_func();
#elif CHECK_JACK(USER)
compile_jack_func();
#elif
#error "unknown user"
#endif
Instead of #define USER 'Q'
#define USER QUEEN
should also work but was not tested also works and might be easier to handle.
EDIT: According to the comment of @Jean-François Fabre I adapted my answer.
Importing Excel files into R, xlsx or xls
I recently discovered Schaun Wheeler's function for importing excel files into R after realising that the xlxs package hadn't been updated for R 3.1.0.
https://gist.github.com/schaunwheeler/5825002
The file name needs to have the ".xlsx" extension and the file can't be open when you run the function.
This function is really useful for accessing other peoples work. The main advantages over using the read.csv function are when
- Importing multiple excel files
- Importing large files
- Files that are updated regularly
Using the read.csv function requires manual opening and saving of each Excel document which is time consuming and very boring. Using Schaun's function to automate the workflow is therefore a massive help.
Big props to Schaun for this solution.
How can I disable editing cells in a WPF Datagrid?
The WPF DataGrid
has an IsReadOnly
property that you can set to True
to ensure that users cannot edit your DataGrid
's cells.
You can also set this value for individual columns in your DataGrid
as needed.
C# Foreach statement does not contain public definition for GetEnumerator
You don't show us the declaration of carBootSaleList
. However from the exception message I can see that it is of type CarBootSaleList
. This type doesn't implement the IEnumerable
interface and therefore cannot be used in a foreach.
Your CarBootSaleList
class should implement IEnumerable<CarBootSale>
:
public class CarBootSaleList : IEnumerable<CarBootSale>
{
private List<CarBootSale> carbootsales;
...
public IEnumerator<CarBootSale> GetEnumerator()
{
return carbootsales.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return carbootsales.GetEnumerator();
}
}
phpinfo() is not working on my CentOS server
It happened to me as well. On a newly provisioned Red Hat Linux 7 server.
When I run a PHP page, i.e. info.php, I could see plain text PHP scripts instead of executing them.
I just installed PHP:
[root@localhost ~]# yum install php
And then restarted Apache HTTP Server:
[root@localhost ~]# systemctl restart httpd
How to filter by string in JSONPath?
I didn't find find the correct jsonpath filter syntax to extract a value from a name-value pair in json.
Here's the syntax and an abbreviated sample twitter document below.
This site was useful for testing:
The jsonpath filter expression:
.events[0].attributes[?(@.name=='screen_name')].value
Test document:
{
"title" : "test twitter",
"priority" : 5,
"events" : [ {
"eventId" : "150d3939-1bc4-4bcb-8f88-6153053a2c3e",
"eventDate" : "2015-03-27T09:07:48-0500",
"publisher" : "twitter",
"type" : "tweet",
"attributes" : [ {
"name" : "filter_level",
"value" : "low"
}, {
"name" : "screen_name",
"value" : "_ziadin"
}, {
"name" : "followers_count",
"value" : "406"
} ]
} ]
}
How to get a unix script to run every 15 seconds?
Since my previous answer I came up with another solution that is different and perhaps better. This code allows processes to be run more than 60 times a minute with microsecond precision. You need the usleep program to make this work. Should be good to up to 50 times a second.
#! /bin/sh
# Microsecond Cron
# Usage: cron-ms start
# Copyright 2014 by Marc Perkel
# docs at http://wiki.junkemailfilter.com/index.php/How_to_run_a_Linux_script_every_few_seconds_under_cron"
# Free to use with attribution
basedir=/etc/cron-ms
if [ $# -eq 0 ]
then
echo
echo "cron-ms by Marc Perkel"
echo
echo "This program is used to run all programs in a directory in parallel every X times per minute."
echo "Think of this program as cron with microseconds resolution."
echo
echo "Usage: cron-ms start"
echo
echo "The scheduling is done by creating directories with the number of"
echo "executions per minute as part of the directory name."
echo
echo "Examples:"
echo " /etc/cron-ms/7 # Executes everything in that directory 7 times a minute"
echo " /etc/cron-ms/30 # Executes everything in that directory 30 times a minute"
echo " /etc/cron-ms/600 # Executes everything in that directory 10 times a second"
echo " /etc/cron-ms/2400 # Executes everything in that directory 40 times a second"
echo
exit
fi
# If "start" is passed as a parameter then run all the loops in parallel
# The number of the directory is the number of executions per minute
# Since cron isn't accurate we need to start at top of next minute
if [ $1 = start ]
then
for dir in $basedir/* ; do
$0 ${dir##*/} 60000000 &
done
exit
fi
# Loops per minute and the next interval are passed on the command line with each loop
loops=$1
next_interval=$2
# Sleeps until a specific part of a minute with microsecond resolution. 60000000 is full minute
usleep $(( $next_interval - 10#$(date +%S%N) / 1000 ))
# Run all the programs in the directory in parallel
for program in $basedir/$loops/* ; do
if [ -x $program ]
then
$program &> /dev/null &
fi
done
# Calculate next_interval
next_interval=$(($next_interval % 60000000 + (60000000 / $loops) ))
# If minute is not up - call self recursively
if [ $next_interval -lt $(( 60000000 / $loops * $loops)) ]
then
. $0 $loops $next_interval &
fi
# Otherwise we're done
SQLAlchemy create_all() does not create tables
This is probably not the main reason why the create_all()
method call doesn't work for people, but for me, the cobbled together instructions from various tutorials have it such that I was creating my db in a request context, meaning I have something like:
# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy
def get_db():
if 'db' not in g:
g.db = SQLAlchemy(current_app)
return g.db
I also have a separate cli command that also does the create_all:
# tasks/db.py
from lib.db import get_db
@current_app.cli.command('init-db')
def init_db():
db = get_db()
db.create_all()
I also am using a application factory.
When the cli command is run, a new app context is used, which means a new db is used. Furthermore, in this world, an import model in the init_db method does not do anything, because it may be that your model file was already loaded(and associated with a separate db).
The fix that I came around to was to make sure that the db was a single global reference:
# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy
db = None
def get_db():
global db
if not db:
db = SQLAlchemy(current_app)
return db
I have not dug deep enough into flask, sqlalchemy, or flask-sqlalchemy to understand if this means that requests to the db from multiple threads are safe, but if you're reading this you're likely stuck in the baby stages of understanding these concepts too.
Targeting both 32bit and 64bit with Visual Studio in same solution/project
Yes, you can target both x86 and x64 with the same code base in the same project. In general, things will Just Work if you create the right solution configurations in VS.NET (although P/Invoke to entirely unmanaged DLLs will most likely require some conditional code): the items that I found to require special attention are:
- References to outside managed assemblies with the same name but their own specific bitness (this also applies to COM interop assemblies)
- The MSI package (which, as has already been noted, will need to target either x86 or x64)
- Any custom .NET Installer Class-based actions in your MSI package
The assembly reference issue can't be solved entirely within VS.NET, as it will only allow you to add a reference with a given name to a project once. To work around this, edit your project file manually (in VS, right-click your project file in the Solution Explorer, select Unload Project, then right-click again and select Edit). After adding a reference to, say, the x86 version of an assembly, your project file will contain something like:
<Reference Include="Filename, ..., processorArchitecture=x86">
<HintPath>C:\path\to\x86\DLL</HintPath>
</Reference>
Wrap that Reference tag inside an ItemGroup tag indicating the solution configuration it applies to, e.g:
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<Reference ...>....</Reference>
</ItemGroup>
Then, copy and paste the entire ItemGroup tag, and edit it to contain the details of your 64-bit DLL, e.g.:
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
<Reference Include="Filename, ..., processorArchitecture=AMD64">
<HintPath>C:\path\to\x64\DLL</HintPath>
</Reference>
</ItemGroup>
After reloading your project in VS.NET, the Assembly Reference dialog will be a bit confused by these changes, and you may encounter some warnings about assemblies with the wrong target processor, but all your builds will work just fine.
Solving the MSI issue is up next, and unfortunately this will require a non-VS.NET tool: I prefer Caphyon's Advanced Installer for that purpose, as it pulls off the basic trick involved (create a common MSI, as well as 32-bit and 64-bit specific MSIs, and use an .EXE setup launcher to extract the right version and do the required fixups at runtime) very, very well.
You can probably achieve the same results using other tools or the Windows Installer XML (WiX) toolset, but Advanced Installer makes things so easy (and is quite affordable at that) that I've never really looked at alternatives.
One thing you may still require WiX for though, even when using Advanced Installer, is for your .NET Installer Class custom actions. Although it's trivial to specify certain actions that should only run on certain platforms (using the VersionNT64 and NOT VersionNT64 execution conditions, respectively), the built-in AI custom actions will be executed using the 32-bit Framework, even on 64-bit machines.
This may be fixed in a future release, but for now (or when using a different tool to create your MSIs that has the same issue), you can use WiX 3.0's managed custom action support to create action DLLs with the proper bitness that will be executed using the corresponding Framework.
Edit: as of version 8.1.2, Advanced Installer correctly supports 64-bit custom actions. Since my original answer, its price has increased quite a bit, unfortunately, even though it's still extremely good value when compared to InstallShield and its ilk...
Edit: If your DLLs are registered in the GAC, you can also use the standard reference tags this way (SQLite as an example):
<ItemGroup Condition="'$(Platform)' == 'x86'">
<Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86" />
</ItemGroup>
<ItemGroup Condition="'$(Platform)' == 'x64'">
<Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=AMD64" />
</ItemGroup>
The condition is also reduced down to all build types, release or debug, and just specifies the processor architecture.
How to write data to a JSON file using Javascript
Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.
For example: in some browser like a Chrome we have today this possibility and we can write with FileSystemFileEntry.createWriter() with client side call, but according to the docu:
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.
For IE (but not MS Edge) we could use ActiveX too, but this is only for this client.
If you want update your JSON file cross-browser you have to use server and client side together.
The client side script
On client side you can make a request to the server and then you have to read the response from server. Or you could read a file with FileReader too. For the cross-browser writing to the file you have to have some server (see below on server part).
var xhr = new XMLHttpRequest(),
jsonArr,
method = "GET",
jsonRequestURL = "SOME_PATH/jsonFile/";
xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
// we convert your JSON into JavaScript object
jsonArr = JSON.parse(xhr.responseText);
// we add new value:
jsonArr.push({"nissan": "sentra", "color": "green"});
// we send with new request the updated JSON file to the server:
xhr.open("POST", jsonRequestURL, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// if you want to handle the POST response write (in this case you do not need it):
// xhr.onreadystatechange = function(){ /* handle POST response */ };
xhr.send("jsonTxt="+JSON.stringify(jsonArr));
// but on this place you have to have a server for write updated JSON to the file
}
};
xhr.send(null);
Server side scripts
You can use a lot of different servers, but I would like to write about PHP and Node.js servers.
By using searching machine you could find "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server I would recommend 000webhost.com and for Node.js I would recommend to see and to read this list.
PHP server side script solution
The PHP script for reading and writing from JSON file:
<?php
// This PHP script must be in "SOME_PATH/jsonFile/index.php"
$file = 'jsonFile.txt';
if($_SERVER['REQUEST_METHOD'] === 'POST')
// or if(!empty($_POST))
{
file_put_contents($file, $_POST["jsonTxt"]);
//may be some error handeling if you want
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
// or else if(!empty($_GET))
{
echo file_get_contents($file);
//may be some error handeling if you want
}
?>
Node.js server side script solution
I think that Node.js is a little bit complex for beginner. This is not normal JavaScript like in browser. Before you start with Node.js I would recommend to read one from two books:
The Node.js script for reading and writing from JSON file:
var http = require("http"),
fs = require("fs"),
port = 8080,
pathToJSONFile = '/SOME_PATH/jsonFile.txt';
http.createServer(function(request, response)
{
if(request.method == 'GET')
{
response.writeHead(200, {"Content-Type": "application/json"});
response.write(fs.readFile(pathToJSONFile, 'utf8'));
response.end();
}
else if(request.method == 'POST')
{
var body = [];
request.on('data', function(chunk)
{
body.push(chunk);
});
request.on('end', function()
{
body = Buffer.concat(body).toString();
var myJSONdata = body.split("=")[1];
fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
});
}
}).listen(port);
Related links for Node.js:
How to find all the subclasses of a class given its name?
New-style classes (i.e. subclassed from object
, which is the default in Python 3) have a __subclasses__
method which returns the subclasses:
class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass
Here are the names of the subclasses:
print([cls.__name__ for cls in Foo.__subclasses__()])
# ['Bar', 'Baz']
Here are the subclasses themselves:
print(Foo.__subclasses__())
# [<class '__main__.Bar'>, <class '__main__.Baz'>]
Confirmation that the subclasses do indeed list Foo
as their base:
for cls in Foo.__subclasses__():
print(cls.__base__)
# <class '__main__.Foo'>
# <class '__main__.Foo'>
Note if you want subsubclasses, you'll have to recurse:
def all_subclasses(cls):
return set(cls.__subclasses__()).union(
[s for c in cls.__subclasses__() for s in all_subclasses(c)])
print(all_subclasses(Foo))
# {<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>}
Note that if the class definition of a subclass hasn't been executed yet - for example, if the subclass's module hasn't been imported yet - then that subclass doesn't exist yet, and __subclasses__
won't find it.
You mentioned "given its name". Since Python classes are first-class objects, you don't need to use a string with the class's name in place of the class or anything like that. You can just use the class directly, and you probably should.
If you do have a string representing the name of a class and you want to find that class's subclasses, then there are two steps: find the class given its name, and then find the subclasses with __subclasses__
as above.
How to find the class from the name depends on where you're expecting to find it. If you're expecting to find it in the same module as the code that's trying to locate the class, then
cls = globals()[name]
would do the job, or in the unlikely case that you're expecting to find it in locals,
cls = locals()[name]
If the class could be in any module, then your name string should contain the fully-qualified name - something like 'pkg.module.Foo'
instead of just 'Foo'
. Use importlib
to load the class's module, then retrieve the corresponding attribute:
import importlib
modname, _, clsname = name.rpartition('.')
mod = importlib.import_module(modname)
cls = getattr(mod, clsname)
However you find the class, cls.__subclasses__()
would then return a list of its subclasses.
javascript - Create Simple Dynamic Array
Update: micro-optimizations like this one are just not worth it, engines are so smart these days that I would advice in the 2020 to simply just go with var arr = [];
.
Here is how I would do it:
var mynumber = 10;
var arr = new Array(mynumber);
for (var i = 0; i < mynumber; i++) {
arr[i] = (i + 1).toString();
}
My answer is pretty much the same of everyone, but note that I did something different:
- It is better if you specify the array length and
don't force it to expand every time
So I created the array with new Array(mynumber);
Importing project into Netbeans
Follow these steps:
- Open Netbeans
- Click File > New Project > JavaFX > JavaFX with existing sources
- Click Next
- Name the project
- Click Next
- Under Source Package Folders click Add Folder
- Select the nbproject folder under the zip file you wish to upload (Note: you need to unzip the folder)
- Click Next
- All the files will be included but you can exclude some if you wish
- Click Finish and the project should be there
If you don't have the source folder added do the following
- Under your projects directory tree right click on Source Packages
- Click New
- Click Java Package and name it with the name of the package the source files have
- Go to the directory location (i.e., using Windows Explorer not Netbeans) of those source files, highlight them all, then drag and drop them under that Java Package you just created
- Click Run
- Click Clean and Build Project
Now you can have fun and run the application.
CSS background-image-opacity?
You can do the faded background with CSS Generated Content
Demo at http://jsfiddle.net/gaby/WktFm/508/
Html
<div class="container">
contents
</div>
Css
.container{
position: relative;
z-index:1;
overflow:hidden; /*if you want to crop the image*/
}
.container:before{
z-index:-1;
position:absolute;
left:0;
top:0;
content: url('path/to/image.ext');
opacity:0.4;
}
But you cannot modify the opacity as we are not allowed to modify generated content..
You could manipulate it with classes and css events though (but not sure if it fits your needs)
for example
.container:hover:before{
opacity:1;
}
UPDATE
You can use css transitions to animate the opacity (again through classes)
demo at http://jsfiddle.net/gaby/WktFm/507/
Adding
-webkit-transition: opacity 1s linear;
-o-transition: opacity 1s linear;
-moz-transition: opacity 1s linear;
transition: opacity 1s linear;
to the .container:before
rule will make the opacity animate to 1 in one second.
Compatibility
- FF 5 (maybe 4 also, but do not have it installed.)
- IE 9 Fails..
- Webkit based browsers fail (Chrome supports it now v26 - maybe earlier versions too, but just checked with my current build), but they are aware and working on it ( https://bugs.webkit.org/show_bug.cgi?id=23209 )
.. so only the latest FF supports it for the moment.. but a nice idea, no ? :)
How can I switch to another branch in git?
I am using this to switch one branch to another anyone you can use it works for me like charm.
git switch [branchName] OR
git checkout [branchName]
ex: git switch develop OR
git checkout develop
How to inspect FormData?
Easy Method
I used this code in angular 8
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
formData.forEach((value,key) => {
console.log(key+value)
});
General guidelines to avoid memory leaks in C++
One technique that has become popular with memory management in C++ is RAII. Basically you use constructors/destructors to handle resource allocation. Of course there are some other obnoxious details in C++ due to exception safety, but the basic idea is pretty simple.
The issue generally comes down to one of ownership. I highly recommend reading the Effective C++ series by Scott Meyers and Modern C++ Design by Andrei Alexandrescu.
CSS align one item right with flexbox
For a terse, pure flexbox option, group the left-aligned items and the right-aligned items:
<div class="wrap">
<div>
<span>One</span>
<span>Two</span>
</div>
<div>Three</div>
</div>
and use space-between
:
.wrap {
display: flex;
background: #ccc;
justify-content: space-between;
}
This way you can group multiple items to the right(or just one).
https://jsfiddle.net/c9mkewwv/3/
JavaScript module pattern with example
In order to approach to Modular design pattern, you need to understand these concept first:
Immediately-Invoked Function Expression (IIFE):
(function() {
// Your code goes here
}());
There are two ways you can use the functions. 1. Function declaration 2. Function expression.
Here are using function expression.
What is namespace?
Now if we add the namespace to the above piece of code then
var anoyn = (function() {
}());
What is closure in JS?
It means if we declare any function with any variable scope/inside another function (in JS we can declare a function inside another function!) then it will count that function scope always. This means that any variable in outer function will be read always. It will not read the global variable (if any) with the same name. This is also one of the objective of using modular design pattern avoiding naming conflict.
var scope = "I am global";
function whatismyscope() {
var scope = "I am just a local";
function func() {return scope;}
return func;
}
whatismyscope()()
Now we will apply these three concepts I mentioned above to define our first modular design pattern:
var modularpattern = (function() {
// your module code goes here
var sum = 0 ;
return {
add:function() {
sum = sum + 1;
return sum;
},
reset:function() {
return sum = 0;
}
}
}());
alert(modularpattern.add()); // alerts: 1
alert(modularpattern.add()); // alerts: 2
alert(modularpattern.reset()); // alerts: 0
jsfiddle for the code above.
The objective is to hide the variable accessibility from the outside world.
Hope this helps. Good Luck.
Writing data to a local text file with javascript
Our HTML:
<div id="addnew">
<input type="text" id="id">
<input type="text" id="content">
<input type="button" value="Add" id="submit">
</div>
<div id="check">
<input type="text" id="input">
<input type="button" value="Search" id="search">
</div>
JS (writing to the txt file):
function writeToFile(d1, d2){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 8, false, 0);
fh.WriteLine(d1 + ',' + d2);
fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
var id = document.getElementById("id").value;
var content = document.getElementById("content").value;
writeToFile(id, content);
}
checking a particular row:
function readFile(){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 1, false, 0);
var lines = "";
while (!fh.AtEndOfStream) {
lines += fh.ReadLine() + "\r";
}
fh.Close();
return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
var input = document.getElementById("input").value;
if (input != "") {
var text = readFile();
var lines = text.split("\r");
lines.pop();
var result;
for (var i = 0; i < lines.length; i++) {
if (lines[i].match(new RegExp(input))) {
result = "Found: " + lines[i].split(",")[1];
}
}
if (result) { alert(result); }
else { alert(input + " not found!"); }
}
}
Put these inside a .hta
file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.
How to make a JSONP request from Javascript without JQuery?
My understanding is that you actually use script tags with JSONP, sooo...
The first step is to create your function that will handle the JSON:
function hooray(json) {
// dealin wit teh jsonz
}
Make sure that this function is accessible on a global level.
Next, add a script element to the DOM:
var script = document.createElement('script');
script.src = 'http://domain.com/?function=hooray';
document.body.appendChild(script);
The script will load the JavaScript that the API provider builds, and execute it.
How to search for a string in cell array in MATLAB?
I see that everybody missed the most important flaw in your code:
strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
should be:
strs = {'HA' 'KU' 'NA' 'MA' 'TATA'}
or
strs = {'HAKUNA' 'MATATA'}
Now if you stick to using
ind=find(ismember(strs,'KU'))
You'll have no worries :).
Deep copy an array in Angular 2 + TypeScript
A clean way of deep copying objects having nested objects inside is by using lodash's cloneDeep method.
For Angular, you can do it like this:
Install lodash with yarn add lodash
or npm install lodash
.
In your component, import cloneDeep
and use it:
import * as cloneDeep from 'lodash/cloneDeep';
...
clonedObject = cloneDeep(originalObject);
It's only 18kb added to your build, well worth for the benefits.
I've also written an article here, if you need more insight on why using lodash's cloneDeep.
Remove part of string after "."
We can pretend they are filenames and remove extensions:
tools::file_path_sans_ext(a)
# [1] "NM_020506" "NM_020519" "NM_001030297" "NM_010281" "NM_011419" "NM_053155"
R : how to simply repeat a command?
You could use replicate
or sapply
:
R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL)))
replicate
is a wrapper for the common use of sapply
for repeated evaluation of an expression (which will usually involve random number generation).
Load HTML File Contents to Div [without the use of iframes]
I'd suggest getting into one of the JS libraries out there. They ensure compatibility so you can get up and running really fast. jQuery and DOJO are both really great. To do what you're trying to do in jQuery, for example, it would go something like this:
<script type="text/javascript" language="JavaScript">
$.ajax({
url: "x.html",
context: document.body,
success: function(response) {
$("#yourDiv").html(response);
}
});
</script>
Integration Testing POSTing an entire object to Spring MVC controller
I think most of these solutions are far too complicated.
I assume that in your test controller you have this
@Autowired
private ObjectMapper objectMapper;
If its a rest service
@Test
public void test() throws Exception {
mockMvc.perform(post("/person"))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(new Person()))
...etc
}
For spring mvc using a posted form I came up with this solution. (Not really sure if its a good idea yet)
private MultiValueMap<String, String> toFormParams(Object o, Set<String> excludeFields) throws Exception {
ObjectReader reader = objectMapper.readerFor(Map.class);
Map<String, String> map = reader.readValue(objectMapper.writeValueAsString(o));
MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
map.entrySet().stream()
.filter(e -> !excludeFields.contains(e.getKey()))
.forEach(e -> multiValueMap.add(e.getKey(), (e.getValue() == null ? "" : e.getValue())));
return multiValueMap;
}
@Test
public void test() throws Exception {
MultiValueMap<String, String> formParams = toFormParams(new Phone(),
Set.of("id", "created"));
mockMvc.perform(post("/person"))
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.params(formParams))
...etc
}
The basic idea is to
- first convert object to json string to get all the field names easily
- convert this json string into a map and dump it into a MultiValueMap
that spring expects. Optionally filter out any fields you dont want to include (Or you could just annotate fields with @JsonIgnore
to avoid this extra step)
Multiple Buttons' OnClickListener() android
You could set the property:
android:onClick="buttonClicked"
in the xml file for each of those buttons, and use this in the java code:
public void buttonClicked(View view) {
if (view.getId() == R.id.button1) {
// button1 action
} else if (view.getId() == R.id.button2) {
//button2 action
} else if (view.getId() == R.id.button3) {
//button3 action
}
}
Test for multiple cases in a switch, like an OR (||)
Since the other answers explained how to do it without actually explaining why it works:
When the switch
executes, it finds the first matching case
statement and then executes each line of code after the switch until it hits either a break
statement or the end of the switch
(or a return
statement to leave the entire containing function). When you deliberately omit the break
so that code under the next case
gets executed too that's called a fall-through. So for the OP's requirement:
switch (pageid) {
case "listing-page":
case "home-page":
alert("hello");
break;
case "details-page":
alert("goodbye");
break;
}
Forgetting to include break
statements is a fairly common coding mistake and is the first thing you should look for if your switch
isn't working the way you expected. For that reason some people like to put a comment in to say "fall through" to make it clear when break statements have been omitted on purpose. I do that in the following example since it is a bit more complicated and shows how some cases can include code to execute before they fall-through:
switch (someVar) {
case 1:
someFunction();
alert("It was 1");
// fall through
case 2:
alert("The 2 case");
// fall through
case 3:
// fall through
case 4:
// fall through
case 5:
alert("The 5 case");
// fall through
case 6:
alert("The 6 case");
break;
case 7:
alert("Something else");
break;
case 8:
// fall through
default:
alert("The end");
break;
}
You can also (optionally) include a default
case, which will be executed if none of the other cases match - if you don't include a default
and no cases match then nothing happens. You can (optionally) fall through to the default case.
So in my second example if someVar
is 1 it would call someFunction()
and then you would see four alerts as it falls through multiple cases some of which have alerts under them. Is someVar
is 3, 4 or 5 you'd see two alerts. If someVar
is 7 you'd see "Something else" and if it is 8 or any other value you'd see "The end".
How can I uninstall npm modules in Node.js?
To uninstall the Node.js module:
npm uninstall <module_name>
This will remove the module from folder node_modules, but not from file package.json. So when we do npm install again it will download the module.
So to remove the module from file package.json, use:
npm uninstall <module_name> --save
This also deletes the dependency from file package.json.
And if you want to uninstall any globally module you can use:
npm -g uninstall <module_name> --save
This will delete the dependency globally.
Post Build exited with code 1
I had to run VS as Administrator to get my post-build copy to an OS protected "..\Common7\IDE\PrivateAssemblies" to work
laravel 5.3 new Auth::routes()
If you are searching these same routes for laravel 7 version you'll find it here Vendor/laravel/ui/src/AuthRouteMethods.php
How do getters and setters work?
You may also want to read "Why getter and setter methods are evil":
Though getter/setter methods are commonplace in Java, they are not particularly object oriented (OO). In fact, they can damage your code's maintainability. Moreover, the presence of numerous getter and setter methods is a red flag that the program isn't necessarily well designed from an OO perspective.
This article explains why you shouldn't use getters and setters (and when you can use them) and suggests a design methodology that will help you break out of the getter/setter mentality.
What does principal end of an association means in 1:1 relationship in Entity framework
In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.
In case of entity framework FK in dependent must also be its PK so in your case you should use:
public class Boo
{
[Key, ForeignKey("Foo")]
public string BooId{get;set;}
public Foo Foo{get;set;}
}
Or fluent mapping
modelBuilder.Entity<Foo>()
.HasOptional(f => f.Boo)
.WithRequired(s => s.Foo);
Multiple Image Upload PHP form with one input
Multipal image uplode with other taBLE
$sql1 = "INSERT INTO event(title) VALUES('$title')";
$result1 = mysqli_query($connection,$sql1) or die(mysqli_error($connection));
$lastid= $connection->insert_id;
foreach ($_FILES["file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK ){
$name = $lastid.$_FILES['file']['name'][$key];
$target_dir = "photo/";
$sql2 = "INSERT INTO photos(image,eventid) VALUES ('".$target_dir.$name."','".$lastid."')";
$result2 = mysqli_query($connection,$sql2) or die(mysqli_error($connection));
move_uploaded_file($_FILES['file']['tmp_name'][$key],$target_dir.$name);
}
}
And how to fetch
$query = "SELECT * FROM event ";
$result = mysqli_query($connection,$query) or die(mysqli_error());
if($result->num_rows > 0) {
while($r = mysqli_fetch_assoc($result)){
$eventid= $r['id'];
$sqli="select id,image from photos where eventid='".$eventid."'";
$resulti=mysqli_query($connection,$sqli);
$image_json_array = array();
while($row = mysqli_fetch_assoc($resulti)){
$image_id = $row['id'];
$image_name = $row['image'];
$image_json_array[] = array("id"=>$image_id,"name"=>$image_name);
}
$msg1[] = array ("imagelist" => $image_json_array);
}
in ajax
$(document).ready(function(){ $('#addCAT').validate({ rules:{name:required:true}submitHandler:function(form){var formurl = $(form).attr('action'); $.ajax({ url: formurl,type: "POST",data: new FormData(form),cache: false,processData: false,contentType: false,success: function(data) {window.location.href="{{ url('admin/listcategory')}}";}});
}
})})
Returning a boolean value in a JavaScript function
You could simplify this a lot:
- Check whether one is not empty
- Check whether they are equal
This will result in this, which will always return a boolean. Your function also should always return a boolean, but you can see it does a little better if you simplify your code:
function validatePassword()
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
return password.value !== "" && password.value === confirm_password.value;
// not empty and equal
}
How to clear PermGen space Error in tomcat
The PermGen space is what Tomcat uses to store class definitions (definitions only, no instantiations) and string pools that have been interned. From experience, the PermGen space issues tend to happen frequently in dev environments really since Tomcat has to load new classes every time it deploys a WAR or does a jspc (when you edit a jsp file). Personally, I tend to deploy and redeploy wars a lot when I’m in dev testing so I know I’m bound to run out sooner or later (primarily because Java’s GC cycles are still kinda crap so if you redeploy your wars quickly and frequently enough, the space fills up faster than they can manage).
This should theoretically be less of an issue in production environments since you (hopefully) don’t change the codebase on a 10 minute basis. If it still occurs, that just means your codebase (and corresponding library dependencies) are too large for the default memory allocation and you’ll just need to mess around with stack and heap allocation. I think the standards are stuff like:
-XX:MaxPermSize=SIZE
I’ve found however the best way to take care of that for good is to allow classes to be unloaded so your PermGen never runs out:
-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled
Stuff like that worked magic for me in the past. One thing tho, there’s a significant performance tradeoff in using those, since permgen sweeps will make like an extra 2 requests for every request you make or something along those lines. You’ll need to balance your use with the tradeoffs.
Mailx send html message
It's easy, if your mailx
command supports the -a
(append header) option:
$ mailx -a 'Content-Type: text/html' -s "my subject" [email protected] < email.html
If it doesn't, try using sendmail
:
# create a header file
$ cat mailheader
To: [email protected]
Subject: my subject
Content-Type: text/html
# send
$ cat mailheader email.html | sendmail -t
How do I fix the multiple-step OLE DB operation errors in SSIS?
For me the answer was that I was passing two parameters to and execute SQL task, but only using one. I was doing some testing and commented out a section of code using the second parameter. I neglected to remove the parameter mapping.
So ensure you are passing in the correct number of parameters in the parameter mapping if you are using the Execute SQL task.
How to include file in a bash shell script
Above answers are correct, but if run script in other folder, there will be some problem.
For example, the a.sh
and b.sh
are in same folder,
a include b with . ./b.sh
to include.
When run script out of the folder, for example with xx/xx/xx/a.sh
, file b.sh
will not found: ./b.sh: No such file or directory
.
I use
. $(dirname "$0")/b.sh
How to prevent vim from creating (and leaving) temporary files?
I made a plugin called "noswapsuck" that only enables the swapfile when the buffer contains unsaved changes. Once changes have been saved, the swapfile is cleared. Hence, swapfiles which contain the same content as the file on disk will be removed.
Get it here: noswapsuck.vim
It has been working well for me, but I have never publicised it before, so I would welcome feedback.
Advantages:
- The only swapfiles that remain on your disk will be important swapfiles that actually differ from the file!
Disadvantages:
If the buffer has a swapfile, it will not be detected when the file is first opened. It will only be detected when swapfile
is enabled, which is when you start to edit the buffer. That is annoyingly late, and will interrupt you. (Solved: We now check for a pre-existing swapfile when a buffer is opened, by temporarily turning the swapfile
option on again.)
If you are working in an environment where you want to minimise disk-writes (e.g. low power, or files mounted over a network, or editing a huge file) then it is not ideal to keep removing and re-creating the swap file on every save and edit. In such situations, you can do:
:let g:NoSwapSuck_CloseSwapfileOnWrite = 0
which will keep the swapfile after a write, but will still remove it when the buffer loses focus.
By the way, I have another little plugin :DiffAgainstFileOnDisk
which can be pretty useful after hitting (r)ecover
, to check if the buffer you recovered is newer or older than the existing file, or identical to it.
How to convert signed to unsigned integer in python
To get the value equivalent to your C cast, just bitwise and with the appropriate mask. e.g. if unsigned long
is 32 bit:
>>> i = -6884376
>>> i & 0xffffffff
4288082920
or if it is 64 bit:
>>> i & 0xffffffffffffffff
18446744073702667240
Do be aware though that although that gives you the value you would have in C, it is still a signed value, so any subsequent calculations may give a negative result and you'll have to continue to apply the mask to simulate a 32 or 64 bit calculation.
This works because although Python looks like it stores all numbers as sign and magnitude, the bitwise operations are defined as working on two's complement values. C stores integers in twos complement but with a fixed number of bits. Python bitwise operators act on twos complement values but as though they had an infinite number of bits: for positive numbers they extend leftwards to infinity with zeros, but negative numbers extend left with ones. The &
operator will change that leftward string of ones into zeros and leave you with just the bits that would have fit into the C value.
Displaying the values in hex may make this clearer (and I rewrote to string of f's as an expression to show we are interested in either 32 or 64 bits):
>>> hex(i)
'-0x690c18'
>>> hex (i & ((1 << 32) - 1))
'0xff96f3e8'
>>> hex (i & ((1 << 64) - 1)
'0xffffffffff96f3e8L'
For a 32 bit value in C, positive numbers go up to 2147483647 (0x7fffffff), and negative numbers have the top bit set going from -1 (0xffffffff) down to -2147483648 (0x80000000). For values that fit entirely in the mask, we can reverse the process in Python by using a smaller mask to remove the sign bit and then subtracting the sign bit:
>>> u = i & ((1 << 32) - 1)
>>> (u & ((1 << 31) - 1)) - (u & (1 << 31))
-6884376
Or for the 64 bit version:
>>> u = 18446744073702667240
>>> (u & ((1 << 63) - 1)) - (u & (1 << 63))
-6884376
This inverse process will leave the value unchanged if the sign bit is 0, but obviously it isn't a true inverse because if you started with a value that wouldn't fit within the mask size then those bits are gone.
Convert generic list to dataset in C#
Have you tried binding the list to the datagridview directly? If not, try that first because it will save you lots of pain. If you have tried it already, please tell us what went wrong so we can better advise you. Data binding gives you different behaviour depending on what interfaces your data object implements. For example, if your data object only implements IEnumerable
(e.g. List
), you will get very basic one-way binding, but if it implements IBindingList
as well (e.g. BindingList
, DataView
), then you get two-way binding.
Ansible - read inventory hosts and variables to group_vars/all file
If you want to have your vars in files under group_vars, just move them here. Vars can be in the inventory ([group:vars] section) but also (and foremost) in files under group_vars
or hosts_vars
.
For instance, with your example above, you can move your vars for group tests
in the file group_vars/tests
:
Inventory file :
[lb]
10.112.84.122
[tomcat]
10.112.84.124
[jboss5]
10.112.84.122
...
[tests:children]
lb
tomcat
jboss5
[default:children]
tests
group_vars/tests
file :
data_base_user=NETWIN-4.3
data_base_password=NETWIN
data_base_encrypted_password=
data_base_host=10.112.69.48
data_base_port=1521
data_base_service=ssdenwdb
data_base_url=jdbc:oracle:thin:@10.112.69.48:1521/ssdenwdb
Difference between two dates in Python
Another short solution:
from datetime import date
def diff_dates(date1, date2):
return abs(date2-date1).days
def main():
d1 = date(2013,1,1)
d2 = date(2013,9,13)
result1 = diff_dates(d2, d1)
print '{} days between {} and {}'.format(result1, d1, d2)
print ("Happy programmer's day!")
main()
Lua string to int
tonumber (e [, base])
tonumber
takes two arguments, first is string which is converted to number and second is base of e
.
Return value tonumber
is in base 10.
If no base
is provided it converts number to base 10.
> a = '101'
> tonumber(a)
101
If base is provided, it converts it to the given base.
> a = '101'
>
> tonumber(a, 2)
5
> tonumber(a, 8)
65
> tonumber(a, 10)
101
> tonumber(a, 16)
257
>
If e
contains invalid character then it returns nil
.
> --[[ Failed because base 2 numbers consist (0 and 1) --]]
> a = '112'
> tonumber(a, 2)
nil
>
> --[[ similar to above one, this failed because --]]
> --[[ base 8 consist (0 - 7) --]]
> --[[ base 10 consist (0 - 9) --]]
> a = 'AB'
> tonumber(a, 8)
nil
> tonumber(a, 10)
nil
> tonumber(a, 16)
171
I answered considering Lua5.3
Comparing two strings in C?
For comparing 2 strings, either use the built in function strcmp()
using header file string.h
if(strcmp(a,b)==0)
printf("Entered strings are equal");
else
printf("Entered strings are not equal");
OR you can write your own function like this:
int string_compare(char str1[], char str2[])
{
int ctr=0;
while(str1[ctr]==str2[ctr])
{
if(str1[ctr]=='\0'||str2[ctr]=='\0')
break;
ctr++;
}
if(str1[ctr]=='\0' && str2[ctr]=='\0')
return 0;
else
return -1;
}
Navigation bar show/hide
To hide Navigation bar :
[self.navigationController setNavigationBarHidden:YES animated:YES];
To show Navigation bar :
[self.navigationController setNavigationBarHidden:NO animated:YES];
How to split one string into multiple variables in bash shell?
If your solution doesn't have to be general, i.e. only needs to work for strings like your example, you could do:
var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)
I chose cut
here because you could simply extend the code for a few more variables...
Getting started with Haskell
Try writing easy programs in it.
You can find sample tasks in various textbooks, probably.
I wouldn't recommend sticking to Haskell/FP textbooks, just try to do simple things with it: calculations, string manipulations, file access.
After I solved a dozen, I've broke the ice :)
After that, read a lot on advanced concepts (Monads, Arrows, IO, recursive data structures), because haskell is infinite and there are a lot of them.
Error: package or namespace load failed for ggplot2 and for data.table
After a wild goose chase with tons of Google searches and burteforce attempts, I think I found how to solve this problem.
Steps undertaken to solve the problem:
- Uninstall R
- Reinstall R
Install ggplot with the dependencies argument to install.packages set to TRUE
install.packages("ggplot2",dependencies = TRUE)
The above step still does NOT include the Rcpp dependency so that has to be manually installed using the following command
install.packages("Rcpp")
However, while the above command successfully downloads Rcpp, for some reason, it fails to explode the ZIP file and install it in my R's library folder citing the following error:
package ‘Rcpp’ successfully unpacked and MD5 sums checked Warning in
install.packages : unable to move temporary installation
‘C:\Root_Prgs\Data_Science_SW\R\R-3.2.3\library\file27b8ef47b6d\Rcpp’
to ‘C:\Root_Prgs\Data_Science_SW\R\R-3.2.3\library\Rcpp’
The downloaded binary packages are in
C:\Users\MY_USER_ID\AppData\Local\Temp\Rtmp25XQ0S\downloaded_packages
- Note that the above output says "Warning" but actually, it is an indication of failure to install the Rcpp package successfully within the repository. I then used the Tools-->Install packages--> From ZIP file and pointed to the location of the "downloaded binary packages" in the message above -
C:\Users\MY_USER_ID\AppData\Local\Temp\Rtmp25XQ0S\downloaded_packages\Rcpp_0.12.3.zip
This led to successful installation of Rcpp in my R\R-3.2.3\library folder, thereby ensuring that Rcpp is now available when I attempt to load the library for ggplot2. I could not do this step in the past because my previous installation of R would throw error stating that Rcpp cannot be imported. However, the same command worked after I uninstalled and reinstalled R, which is ODD.
install.packages("C:/Users/MY_USER_ID/AppData/Local/Temp/Rtmp25XQ0S/downloaded_packages/Rcpp_0.12.3.zip", repos = NULL, type = "win.binary")
package ‘Rcpp’ successfully unpacked and MD5 sums checked`
I was finally able to load the ggplot2 library successfully.
library(ggplot2)
Select rows of a matrix that meet a condition
This is easier to do if you convert your matrix to a data frame using as.data.frame(). In that case the previous answers (using subset or m$three) will work, otherwise they will not.
To perform the operation on a matrix, you can define a column by name:
m[m[, "three"] == 11,]
Or by number:
m[m[,3] == 11,]
Note that if only one row matches, the result is an integer vector, not a matrix.
T-SQL split string
You can Use this function:
CREATE FUNCTION SplitString
(
@Input NVARCHAR(MAX),
@Character CHAR(1)
)
RETURNS @Output TABLE (
Item NVARCHAR(1000)
)
AS
BEGIN
DECLARE @StartIndex INT, @EndIndex INT
SET @StartIndex = 1
IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
BEGIN
SET @Input = @Input + @Character
END
WHILE CHARINDEX(@Character, @Input) > 0
BEGIN
SET @EndIndex = CHARINDEX(@Character, @Input)
INSERT INTO @Output(Item)
SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)
SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
END
RETURN
END
GO
no operator "<<" matches these operands
You're not including the standard <string>
header.
You got [un]lucky that some of its pertinent definitions were accidentally made available by the other standard headers that you did include ... but operator<<
was not.
How to find char in string and get all the indexes?
This is because str.index(ch)
will return the index where ch
occurs the first time. Try:
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
This will return a list of all indexes you need.
P.S. Hugh's answer shows a generator function (it makes a difference if the list of indexes can get large). This function can also be adjusted by changing []
to ()
.
How to search a specific value in all tables (PostgreSQL)?
Here's a pl/pgsql function that locates records where any column contains a specific value.
It takes as arguments the value to search in text format, an array of table names to search into (defaults to all tables) and an array of schema names (defaults all schema names).
It returns a table structure with schema, name of table, name of column and pseudo-column ctid
(non-durable physical location of the row in the table, see System Columns)
CREATE OR REPLACE FUNCTION search_columns(
needle text,
haystack_tables name[] default '{}',
haystack_schema name[] default '{}'
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
begin
FOR schemaname,tablename,columnname IN
SELECT c.table_schema,c.table_name,c.column_name
FROM information_schema.columns c
JOIN information_schema.tables t ON
(t.table_name=c.table_name AND t.table_schema=c.table_schema)
JOIN information_schema.table_privileges p ON
(t.table_name=p.table_name AND t.table_schema=p.table_schema
AND p.privilege_type='SELECT')
JOIN information_schema.schemata s ON
(s.schema_name=t.table_schema)
WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
AND (c.table_schema=ANY(haystack_schema) OR haystack_schema='{}')
AND t.table_type='BASE TABLE'
LOOP
FOR rowctid IN
EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
schemaname,
tablename,
columnname,
needle
)
LOOP
-- uncomment next line to get some progress report
-- RAISE NOTICE 'hit in %.%', schemaname, tablename;
RETURN NEXT;
END LOOP;
END LOOP;
END;
$$ language plpgsql;
See also the version on github based on the same principle but adding some speed and reporting improvements.
Examples of use in a test database:
- Search in all tables within public schema:
select * from search_columns('foobar');
schemaname | tablename | columnname | rowctid
------------+-----------+------------+---------
public | s3 | usename | (0,11)
public | s2 | relname | (7,29)
public | w | body | (0,2)
(3 rows)
- Search in a specific table:
select * from search_columns('foobar','{w}');
schemaname | tablename | columnname | rowctid
------------+-----------+------------+---------
public | w | body | (0,2)
(1 row)
- Search in a subset of tables obtained from a select:
select * from search_columns('foobar', array(select table_name::name from information_schema.tables where table_name like 's%'), array['public']);
schemaname | tablename | columnname | rowctid
------------+-----------+------------+---------
public | s2 | relname | (7,29)
public | s3 | usename | (0,11)
(2 rows)
- Get a result row with the corresponding base table and and ctid:
select * from public.w where ctid='(0,2)';
title | body | tsv
-------+--------+---------------------
toto | foobar | 'foobar':2 'toto':1
Variants
To test against a regular expression instead of strict equality, like grep, this part of the query:
SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L
may be changed to:
SELECT ctid FROM %I.%I WHERE cast(%I as text) ~ %L
For case insensitive comparisons, you could write:
SELECT ctid FROM %I.%I WHERE lower(cast(%I as text)) = lower(%L)
Solution to "subquery returns more than 1 row" error
When one gets the error 'sub-query returns more than 1 row', the database is actually telling you that there is an unresolvable circular reference. It's a bit like using a spreadsheet and saying cell A1 = B1 and then saying B1 = A1. This error is typically associated with a scenario where one needs to have a double nested sub-query. I would recommend you look up a thing called a 'cross-tab query' this is the type of query one normally needs to solve this problem. It's basically an outer join (left or right) nested inside a sub-query or visa versa. One can also solve this problem with a double join (also considered to be a type of cross-tab query) such as below:
CREATE DEFINER=`root`@`localhost` PROCEDURE `SP_GET_VEHICLES_IN`(
IN P_email VARCHAR(150),
IN P_credentials VARCHAR(150)
)
BEGIN
DECLARE V_user_id INT(11);
SET V_user_id = (SELECT user_id FROM users WHERE email = P_email AND credentials = P_credentials LIMIT 1);
SELECT vehicles_in.vehicle_id, vehicles_in.make_id, vehicles_in.model_id, vehicles_in.model_year,
vehicles_in.registration, vehicles_in.date_taken, make.make_label, model.model_label
FROM make
LEFT OUTER JOIN vehicles_in ON vehicles_in.make_id = make.make_id
LEFT OUTER JOIN model ON model.make_id = make.make_id AND vehicles_in.model_id = model.model_id
WHERE vehicles_in.user_id = V_user_id;
END
In the code above notice that there are three tables in amongst the SELECT clause and these three tables show up after the FROM clause and after the two LEFT OUTER JOIN clauses, these three tables must be distinct amongst the FROM and LEFT OUTER JOIN clauses to be syntactically correct.
It is noteworthy that this is a very important construct to know as a developer especially if you're writing periodical report queries and it's probably the most important skill for any complex cross referencing, so all developers should study these constructs (cross-tab and double join).
Another thing I must warn about is: If you are going to use a cross-tab as a part of a working system and not just a periodical report, you must check the record count and reconfigure the join conditions until the minimum records are returned, otherwise large tables and cross-tabs can grind your server to a halt.
Hope this helps.
Tracking Google Analytics Page Views with AngularJS
In your index.html
, copy and paste the ga snippet but remove the line ga('send', 'pageview');
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-X');
</script>
I like to give it it's own factory file my-google-analytics.js
with self injection:
angular.module('myApp')
.factory('myGoogleAnalytics', [
'$rootScope', '$window', '$location',
function ($rootScope, $window, $location) {
var myGoogleAnalytics = {};
/**
* Set the page to the current location path
* and then send a pageview to log path change.
*/
myGoogleAnalytics.sendPageview = function() {
if ($window.ga) {
$window.ga('set', 'page', $location.path());
$window.ga('send', 'pageview');
}
}
// subscribe to events
$rootScope.$on('$viewContentLoaded', myGoogleAnalytics.sendPageview);
return myGoogleAnalytics;
}
])
.run([
'myGoogleAnalytics',
function(myGoogleAnalytics) {
// inject self
}
]);
jQuery has deprecated synchronous XMLHTTPRequest
To avoid this warning, do not use:
async: false
in any of your $.ajax()
calls. This is the only feature of XMLHttpRequest
that's deprecated.
The default is async: true
, so if you never use this option at all, your code should be safe if the feature is ever really removed.
However, it probably won't be -- it may be removed from the standards, but I'll bet browsers will continue to support it for many years. So if you really need synchronous AJAX for some reason, you can use async: false
and just ignore the warnings. But there are good reasons why synchronous AJAX is considered poor style, so you should probably try to find a way to avoid it. And the people who wrote Flash applications probably never thought it would go away, either, but it's in the process of being phased out now.
Notice that the Fetch
API that's replacing XMLHttpRequest
does not even offer a synchronous option.
ImportError: No module named _ssl
If you built Python from source, this is just a matter of dependencies: since you miss OpenSSL lib installed, python silently fails installing the _ssl module. You can see it in the final report of the make command:
Python build finished, but the necessary bits to build these modules were not found:
_bsddb _sqlite3 _ssl
_tkinter bsddb185 dbm
dl gdbm imageop
sunaudiodev
To find the necessary bits, look in setup.py in detect_modules() for the module's name.
Installing OpenSSL lib in any of the standard lib paths (/usr/lib
, /usr/local/lib
...) should do the trick. Anyway this is how I did :-)
How do I perform a Perl substitution on a string while keeping the original?
If you write Perl with use strict;
, then you'll find that the one line syntax isn't valid, even when declared.
With:
my ($newstring = $oldstring) =~ s/foo/bar/;
You get:
Can't declare scalar assignment in "my" at script.pl line 7, near ") =~"
Execution of script.pl aborted due to compilation errors.
Instead, the syntax that you have been using, while a line longer, is the syntactically correct way to do it with use strict;
. For me, using use strict;
is just a habit now. I do it automatically. Everyone should.
#!/usr/bin/env perl -wT
use strict;
my $oldstring = "foo one foo two foo three";
my $newstring = $oldstring;
$newstring =~ s/foo/bar/g;
print "$oldstring","\n";
print "$newstring","\n";
How do I compare a value to a backslash?
When you only need to check for equality, you can also simply use the in
operator to do a membership test in a sequence of accepted elements:
if message.value[0] in ('/', '\\'):
do_stuff()
Selection with .loc in python
Whenever slicing (a:n
) can be used, it can be replaced by fancy indexing (e.g. [a,b,c,...,n]
). Fancy indexing is nothing more than listing explicitly all the index values instead of specifying only the limits.
Whenever fancy indexing can be used, it can be replaced by a list of Boolean values (a mask) the same size than the index. The value will be True
for index values that would have been included in the fancy index, and False
for the values that would have been excluded. It's another way of listing some index values, but which can be easily automated in NumPy and Pandas, e.g by a logical comparison (like in your case).
The second replacement possibility is the one used in your example. In:
iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
the mask
iris_data['class'] == 'versicolor'
is a replacement for a long and silly fancy index which would be list of row numbers where class
column (a Series) has the value versicolor
.
Whether a Boolean mask appears within a .iloc
or .loc
(e.g. df.loc[mask]
) indexer or directly as the index (e.g. df[mask]
) depends on wether a slice is allowed as a direct index. Such cases are shown in the following indexer cheat-sheet:
Pandas indexers loc and iloc cheat-sheet
inner join in linq to entities
Not 100% sure about the relationship between these two entities but here goes:
IList<Splitting> res = (from s in [data source]
where s.Customer.CompanyID == [companyID] &&
s.CustomerID == [customerID]
select s).ToList();
IList<Splitting> res = [data source].Splittings.Where(
x => x.Customer.CompanyID == [companyID] &&
x.CustomerID == [customerID]).ToList();
find first sequence item that matches a criterion
If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:
next(obj for obj in objs if obj.val == 5)
This is however faster than a complete list comprehension. Compare these two:
[i for i in xrange(100000) if i == 1000][0]
next(i for i in xrange(100000) if i == 1000)
The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).
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 :)
ASP.NET strange compilation error
I have crawled through a lot of blog posts including a few Stack Overflow pots, and I already had everything in place what these posts suggested (see below) when I got this error.
- My app pool is running under ApplicationPoolIdentity
- Load user Profile was set to True in Process Model section
- IIS AppPool\DefaultAppPool has full permissions on temp ASP.NET files folder
Finally I found some clues in the below mentioned blog post. It looks like there is heap contention with the same user account. So I changed the app pool identity to LocalSystem, for the app which is failing with this error - and my app started working fine.
See blog post C# compiler or Visual Basic .Net compilers fail with error code -1073741502 when generating assemblies for your ASP.net site.
Note: LocalSystem account will not have much permissions. In my case my application does not need any special permissions. So I was fine. If your application needs special permissions try configuring a custom account.
How to find which views are using a certain table in SQL Server (2008)?
To find table dependencies you can use the sys.sql_expression_dependencies catalog view:
SELECT
referencing_object_name = o.name,
referencing_object_type_desc = o.type_desc,
referenced_object_name = referenced_entity_name,
referenced_object_type_desc =so1.type_desc
FROM sys.sql_expression_dependencies sed
INNER JOIN sys.views o ON sed.referencing_id = o.object_id
LEFT OUTER JOIN sys.views so1 ON sed.referenced_id =so1.object_id
WHERE referenced_entity_name = 'Person'
You can also try out ApexSQL Search a free SSMS and VS add-in that also has the View Dependencies feature. The View Dependencies feature has the ability to visualize all SQL database objects’ relationships, including those between encrypted and system objects, SQL server 2012 specific objects, and objects stored in databases encrypted with Transparent Data Encryption (TDE)
Disclaimer: I work for ApexSQL as a Support Engineer
HTTP status code for update and delete?
Here are some Tips:
DELETE
200 (if you want send some additional data in the Response) or 204 (recommended).
202 Operation deleted has not been committed yet.
If there's nothing to delete, use 204 or 404 (DELETE operation is idempotent, delete an already deleted item is operation successful, so you can return 204, but it's true that idempotent doesn't necessarily imply the same response)
Other errors:
- 400 Bad Request (Malformed syntax or a bad query is strange but possible).
- 401 Unauthorized Authentication failure
- 403 Forbidden: Authorization failure or invalid Application ID.
- 405 Not Allowed. Sure.
- 409 Resource Conflict can be possible in complex systems.
- And 501, 502 in case of errors.
PUT
If you're updating an element of a collection
- 200/204 with the same reasons as DELETE above.
- 202 if the operation has not been commited yet.
The referenced element doesn't exists:
PUT can be 201 (if you created the element because that is your behaviour)
404 If you don't want to create elements via PUT.
400 Bad Request (Malformed syntax or a bad query more common than in case of DELETE).
401 Unauthorized
403 Forbidden: Authentication failure or invalid Application ID.
405 Not Allowed. Sure.
409 Resource Conflict can be possible in complex systems, as in DELETE.
422 Unprocessable entity It helps to distinguish between a "Bad request" (e.g. malformed XML/JSON) and invalid field values
And 501, 502 in case of errors.
How to move an element into another element?
What about a JavaScript solution?
// Declare a fragment:
var fragment = document.createDocumentFragment();
// Append desired element to the fragment:
fragment.appendChild(document.getElementById('source'));
// Append fragment to desired element:
document.getElementById('destination').appendChild(fragment);
Check it out.
Select columns in PySpark dataframe
The method select
accepts a list of column names (string) or expressions (Column) as a parameter. To select columns you can use:
-- column names (strings):
df.select('col_1','col_2','col_3')
-- column objects:
import pyspark.sql.functions as F
df.select(F.col('col_1'), F.col('col_2'), F.col('col_3'))
# or
df.select(df.col_1, df.col_2, df.col_3)
# or
df.select(df['col_1'], df['col_2'], df['col_3'])
-- a list of column names or column objects:
df.select(*['col_1','col_2','col_3'])
#or
df.select(*[F.col('col_1'), F.col('col_2'), F.col('col_3')])
#or
df.select(*[df.col_1, df.col_2, df.col_3])
The star operator *
can be omitted as it's used to keep it consistent with other functions like drop
that don't accept a list as a parameter.
Python function to convert seconds into minutes, hours, and days
The "timeit" answer above that declares divmod to be slower has seriously flawed logic.
Test1 calls operators.
Test2 calls the function divmod,
and calling a function has overhead.
A more accurate way to test would be:
import timeit
def moddiv(a,b):
q= a/b
r= a%b
return q,r
a=10
b=3
md=0
dm=0
for i in range(1,10):
c=a*i
md+= timeit.timeit( lambda: moddiv(c,b))
dm+=timeit.timeit( lambda: divmod(c,b))
print("moddiv ", md)
print("divmod ", dm)
moddiv 5.806157339000492
divmod 4.322451676005585
divmod is faster.
TypeError: Can't convert 'int' object to str implicitly
You cannot concatenate a string
with an int
. You would need to convert your int
to a string
using the str
function, or use formatting
to format your output.
Change: -
print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")
to: -
print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))
or: -
print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")
or as per the comment, use ,
to pass different strings to your print
function, rather than concatenating using +
: -
print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")
Compare dates with javascript
The best way is,
var first = '2012-11-21';
var second = '2012-11-03';
if (new Date(first) > new Date(second) {
.....
}
foreach for JSON array , syntax
You can do something like
for(var k in result) {
console.log(k, result[k]);
}
which loops over all the keys in the returned json and prints the values. However, if you have a nested structure, you will need to use
typeof result[k] === "object"
to determine if you have to loop over the nested objects. Most APIs I have used, the developers know the structure of what is being returned, so this is unnecessary. However, I suppose it's possible that this expectation is not good for all cases.
Color text in discord
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Option #1 (Markdown code-blocks)
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Option #2 (Embeds)
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
(Embed Cheat-sheet)
Retrofit 2.0 how to get deserialised error response.body
In Kotlin:
val call = APIClient.getInstance().signIn(AuthRequestWrapper(AuthRequest("1234567890z", "12341234", "nonce")))
call.enqueue(object : Callback<AuthResponse> {
override fun onResponse(call: Call<AuthResponse>, response: Response<AuthResponse>) {
if (response.isSuccessful) {
} else {
val a = object : Annotation{}
val errorConverter = RentalGeekClient.getRetrofitInstance().responseBodyConverter<AuthFailureResponse>(AuthFailureResponse::class.java, arrayOf(a))
val authFailureResponse = errorConverter.convert(response.errorBody())
}
}
override fun onFailure(call: Call<AuthResponse>, t: Throwable) {
}
})
Importing lodash into angular2 + typescript application
Managing types via typings
and tsd
commands is ultimately deprecated in favor of using npm via npm install @types/lodash
.
However, I struggled with "Cannot find module lodash" in import statement for a long time:
import * as _ from 'lodash';
Ultimately I realized Typescript will only load types from node_modules/@types start version 2, and my VsCode Language service was still using 1.8, so the editor was reporting errors.
If you're using VSCode you'll want to include
"typescript.tsdk": "node_modules/typescript/lib"
in your VSCode settings.json file (for workspace settings) and make sure you have typescript version >= 2.0.0 installed via npm install [email protected] --save-dev
After that my editor wouldn't complain about the import statement.
Saving an Excel sheet in a current directory with VBA
I am not clear exactly what your situation requires but the following may get you started. The key here is using ThisWorkbook.Path
to get a relative file path:
Sub SaveToRelativePath()
Dim relativePath As String
relativePath = ThisWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
ActiveWorkbook.SaveAs Filename:=relativePath
End Sub
Installation Issue with matplotlib Python
Problem Cause
In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.
Solution
- I assume you have installed the pip matplotlib, there is a directory in your root called
~/.matplotlib
.
- Create a file
~/.matplotlib/matplotlibrc
there and add the following code: backend: TkAgg
From this link you can try different diagrams.
Append an int to a std::string
You are casting ClientID
to char* causing the function to assume its a null terinated char array, which it is not.
from cplusplus.com :
string& append ( const char * s ); Appends a copy of the string formed
by the null-terminated character sequence (C string) pointed by s. The
length of this character sequence is determined by the first ocurrence
of a null character (as determined by traits.length(s)).
jQuery: Check if button is clicked
jQuery(':button').click(function () {
if (this.id == 'button1') {
alert('Button 1 was clicked');
}
else if (this.id == 'button2') {
alert('Button 2 was clicked');
}
});
EDIT:- This will work for all buttons.
Pandas - Get first row value of a given column
To select the ith
row, use iloc
:
In [31]: df_test.iloc[0]
Out[31]:
ATime 1.2
X 2.0
Y 15.0
Z 2.0
Btime 1.2
C 12.0
D 25.0
E 12.0
Name: 0, dtype: float64
To select the ith value in the Btime
column you could use:
In [30]: df_test['Btime'].iloc[0]
Out[30]: 1.2
There is a difference between df_test['Btime'].iloc[0]
(recommended) and df_test.iloc[0]['Btime']
:
DataFrames store data in column-based blocks (where each block has a single
dtype). If you select by column first, a view can be returned (which is
quicker than returning a copy) and the original dtype is preserved. In contrast,
if you select by row first, and if the DataFrame has columns of different
dtypes, then Pandas copies the data into a new Series of object dtype. So
selecting columns is a bit faster than selecting rows. Thus, although
df_test.iloc[0]['Btime']
works, df_test['Btime'].iloc[0]
is a little bit
more efficient.
There is a big difference between the two when it comes to assignment.
df_test['Btime'].iloc[0] = x
affects df_test
, but df_test.iloc[0]['Btime']
may not. See below for an explanation of why. Because a subtle difference in
the order of indexing makes a big difference in behavior, it is better to use single indexing assignment:
df.iloc[0, df.columns.get_loc('Btime')] = x
df.iloc[0, df.columns.get_loc('Btime')] = x
(recommended):
The recommended way to assign new values to a
DataFrame is to avoid chained indexing, and instead use the method shown by
andrew,
df.loc[df.index[n], 'Btime'] = x
or
df.iloc[n, df.columns.get_loc('Btime')] = x
The latter method is a bit faster, because df.loc
has to convert the row and column labels to
positional indices, so there is a little less conversion necessary if you use
df.iloc
instead.
df['Btime'].iloc[0] = x
works, but is not recommended:
Although this works, it is taking advantage of the way DataFrames are currently implemented. There is no guarantee that Pandas has to work this way in the future. In particular, it is taking advantage of the fact that (currently) df['Btime']
always returns a
view (not a copy) so df['Btime'].iloc[n] = x
can be used to assign a new value
at the nth location of the Btime
column of df
.
Since Pandas makes no explicit guarantees about when indexers return a view versus a copy, assignments that use chained indexing generally always raise a SettingWithCopyWarning
even though in this case the assignment succeeds in modifying df
:
In [22]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
In [24]: df['bar'] = 100
In [25]: df['bar'].iloc[0] = 99
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self._setitem_with_indexer(indexer, value)
In [26]: df
Out[26]:
foo bar
0 A 99 <-- assignment succeeded
2 B 100
1 C 100
df.iloc[0]['Btime'] = x
does not work:
In contrast, assignment with df.iloc[0]['bar'] = 123
does not work because df.iloc[0]
is returning a copy:
In [66]: df.iloc[0]['bar'] = 123
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
In [67]: df
Out[67]:
foo bar
0 A 99 <-- assignment failed
2 B 100
1 C 100
Warning: I had previously suggested df_test.ix[i, 'Btime']
. But this is not guaranteed to give you the ith
value since ix
tries to index by label before trying to index by position. So if the DataFrame has an integer index which is not in sorted order starting at 0, then using ix[i]
will return the row labeled i
rather than the ith
row. For example,
In [1]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
In [2]: df
Out[2]:
foo
0 A
2 B
1 C
In [4]: df.ix[1, 'foo']
Out[4]: 'C'
Converting Dictionary to List?
Converting from dict to list is made easy in Python. Three examples:
>> d = {'a': 'Arthur', 'b': 'Belling'}
>> d.items()
[('a', 'Arthur'), ('b', 'Belling')]
>> d.keys()
['a', 'b']
>> d.values()
['Arthur', 'Belling']
How to make Scrollable Table with fixed headers using CSS
I can think of a cheeky way to do it, I don't think this will be the best option but it will work.
Create the header as a separate table then place the other in a div and set a max size, then allow the scroll to come in by using overflow
.
_x000D_
_x000D_
table {_x000D_
width: 500px;_x000D_
}_x000D_
_x000D_
.scroll {_x000D_
max-height: 60px;_x000D_
overflow: auto;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<th>head1</th>_x000D_
<th>head2</th>_x000D_
<th>head3</th>_x000D_
<th>head4</th>_x000D_
</tr>_x000D_
</table>_x000D_
<div class="scroll">_x000D_
<table>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>_x000D_
</table>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Count character occurrences in a string in C++
You can find out occurrence of '_' in source string by using string functions.
find() function takes 2 arguments , first - string whose occurrences we want to find out and second argument takes starting position.While loop is use to find out occurrence till the end of source string.
example:
string str2 = "_";
string strData = "bla_bla_blabla_bla_";
size_t pos = 0,pos2;
while ((pos = strData.find(str2, pos)) < strData.length())
{
printf("\n%d", pos);
pos += str2.length();
}
Cygwin - Makefile-error: recipe for target `main.o' failed
You see the two empty -D
entries in the g++
command line? They're causing the problem. You must have values in the -D
items e.g. -DWIN32
if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:
SYSTEM ?= generic
ENVIRONMENT ?= generic
in the makefile which gives them default values.
Your output looks to be missing the all important output:
<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers
just to clarify, what actually got sent to g++
was -D -DWindows_NT
, i.e. define a preprocessor macro called -DWindows_NT
; which is of course not a valid identifier (similarly for -D -I.
)
All combinations of a list of lists
Numpy can do it:
>>> import numpy
>>> a = [[1,2,3],[4,5,6],[7,8,9,10]]
>>> [list(x) for x in numpy.array(numpy.meshgrid(*a)).T.reshape(-1,len(a))]
[[ 1, 4, 7], [1, 5, 7], [1, 6, 7], ....]
ConcurrentModificationException for ArrayList
You can't remove from list if you're browsing it with "for each" loop. You can use Iterator
. Replace:
for (DrugStrength aDrugStrength : aDrugStrengthList) {
if (!aDrugStrength.isValidDrugDescription()) {
aDrugStrengthList.remove(aDrugStrength);
}
}
With:
for (Iterator<DrugStrength> it = aDrugStrengthList.iterator(); it.hasNext(); ) {
DrugStrength aDrugStrength = it.next();
if (!aDrugStrength.isValidDrugDescription()) {
it.remove();
}
}
Disabling buttons on react native
this native-base there is solution:
<Button
block
disabled={!learnedWordsByUser.length}
style={{ marginTop: 10 }}
onPress={learnedWordsByUser.length && () => {
onFlipCardsGenerateNewWords(learnedWordsByUser)
onFlipCardsBtnPress()
}}
>
<Text>Let's Review</Text>
</Button>
Difference between res.send and res.json in Express.js
Looking in the headers sent...
res.send uses content-type:text/html
res.json uses content-type:application/json
edit: send actually changes what is sent based on what it's given, so strings are sent as text/html, but it you pass it an object it emits application/json.
create a white rgba / CSS3
The code you have is a white with low opacity.
If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.
Here is a simple demo.
If you want it to look 'more white', make it less opaque:
background:rgba(255,255,255, 0.9);
Demo
Java: using switch statement with enum under subclass
This is how I am using it. And it is working fantastically -
public enum Button {
REPORT_ISSUES(0),
CANCEL_ORDER(1),
RETURN_ORDER(2);
private int value;
Button(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
And the switch-case
as shown below
@Override
public void onClick(MyOrderDetailDelgate.Button button, int position) {
switch (button) {
case REPORT_ISSUES: {
break;
}
case CANCEL_ORDER: {
break;
}
case RETURN_ORDER: {
break;
}
}
}
How to specify in crontab by what user to run script?
Instead of creating a crontab to run as the root user, create a crontab for the user that you want to run the script. In your case, crontab -u www-data -e
will edit the crontab for the www-data user. Just put your full command in there and remove it from the root user's crontab.
Inserting a Python datetime.datetime object into MySQL
You are most likely getting the TypeError because you need quotes around the datecolumn value.
Try:
now = datetime.datetime(2009, 5, 5)
cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, '%s')",
("name", 4, now))
With regards to the format, I had success with the above command (which includes the milliseconds) and with:
now.strftime('%Y-%m-%d %H:%M:%S')
Hope this helps.
remove item from stored array in angular 2
I think the Angular 2 way of doing this is the filter method:
this.data = this.data.filter(item => item !== data_item);
where data_item is the item that should be deleted
How can I find my php.ini on wordpress?
I just came across this thread while searching for an answer to why the php.ini file would be within the /wp-admin/ folder for WordPress that I have just seen in an odd setup - because it really really shouldn't be there.
WordPress by default doesn't include a php.ini file within the /wp-admin/ folder, so you should not have one there yourself. The php.ini file is designed to override the main server PHP configuration settings so that your account on the server is treated differently, within limits. As such, if you do need to use this file, please, for your own sanity (and that of others who happen to work with your systems in the future...), place the php.ini file in the root of your account, not hidden away in the /wp-admin/ folder, or any other folder for that matter.
I'm surprised to see so many others commenting that it should be in the /wp-admin/ folder to be honest. I'd love to see some official documentation from WordPress stating that this is best practice, as this is certainly something that I would completely avoid.
jquery $.each() for objects
$.each()
works for objects and arrays both:
var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };
$.each(data.programs, function (i) {
$.each(data.programs[i], function (key, val) {
alert(key + val);
});
});
...and since you will get the current array element as second argument:
$.each(data.programs, function (i, currProgram) {
$.each(currProgram, function (key, val) {
alert(key + val);
});
});
How to read integer value from the standard input in Java
Second answer above is the most simple one.
int n = Integer.parseInt(System.console().readLine());
The question is "How to read from standard input".
A console is a device typically associated to the keyboard and display from which a program is launched.
You may wish to test if no Java console device is available, e.g. Java VM not started from a command line or the standard input and output streams are redirected.
Console cons;
if ((cons = System.console()) == null) {
System.err.println("Unable to obtain console");
...
}
Using console is a simple way to input numbers. Combined with parseInt()/Double() etc.
s = cons.readLine("Enter a int: ");
int i = Integer.parseInt(s);
s = cons.readLine("Enter a double: ");
double d = Double.parseDouble(s);
Static methods - How to call a method from another method?
OK the main difference between class methods and static methods is:
- class method has its own identity, that's why they have to be called from within an INSTANCE.
- on the other hand static method can be shared between multiple instances so that it must be called from within THE CLASS
How to check if a subclass is an instance of a class at runtime?
You have to read the API carefully for this methods. Sometimes you can get confused very easily.
It is either:
if (B.class.isInstance(view))
API says: Determines if the specified Object (the parameter) is assignment-compatible with the object represented by this Class (The class object you are calling the method at)
or:
if (B.class.isAssignableFrom(view.getClass()))
API says: Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter
or (without reflection and the recommended one):
if (view instanceof B)
What is the Simplest Way to Reverse an ArrayList?
Simple way is that you have "Collections" in Java. You just need to call it and use "reverse()" method of it.
Example usage:
ArrayList<Integer> yourArrayList = new ArrayList<>();
yourArrayList.add(1);
yourArrayList.add(2);
yourArrayList.add(3);
//yourArrayList is: 1,2,3
Collections.reverse(yourArrayList);
// Now, yourArrayList is: 3,2,1
For more question: @canerkaseler
Disable double-tap "zoom" option in browser on touch devices
This will prevent double tap zoom on elements in 'body' this can be changed to any other selector
$('body').bind('touchstart', function preventZoom(e){
var t2 = e.timeStamp;
var t1 = $(this).data('lastTouch') || t2;
var dt = t2 - t1;
var fingers = e.originalEvent.touches.length;
$(this).data('lastTouch', t2);
if (!dt || dt > 500 || fingers > 1){
return; // not double-tap
}
e.preventDefault(); // double tap - prevent the zoom
// also synthesize click events we just swallowed up
$(e.target).trigger('click');
});
But this also prevented my click event from triggering when clicked multiple times so i had to bind a another event to trigger the events on multiple clicks
$('.selector').bind('touchstart click', preventZoom(e) {
e.stopPropagation(); //stops propagation
if(e.type == "touchstart") {
// Handle touchstart event.
} else if(e.type == "click") {
// Handle click event.
}
});
On touchstart i added the code to prevent the zoom and trigger a click.
$('.selector').bind('touchstart, click', function preventZoom(e){
e.stopPropagation(); //stops propagation
if(e.type == "touchstart") {
// Handle touchstart event.
var t2 = e.timeStamp;
var t1 = $(this).data('lastTouch') || t2;
var dt = t2 - t1;
var fingers = e.originalEvent.touches.length;
$(this).data('lastTouch', t2);
if (!dt || dt > 500 || fingers > 1){
return; // not double-tap
}
e.preventDefault(); // double tap - prevent the zoom
// also synthesize click events we just swallowed up
$(e.target).trigger('click');
} else if(e.type == "click") {
// Handle click event.
"Put your events for click and touchstart here"
}
});
Switch role after connecting to database
--create a user that you want to use the database as:
create role neil;
--create the user for the web server to connect as:
create role webgui noinherit login password 's3cr3t';
--let webgui set role to neil:
grant neil to webgui; --this looks backwards but is correct.
webgui
is now in the neil
group, so webgui
can call set role neil
. However, webgui
did not inherit neil
's permissions.
Later, login as webgui:
psql -d some_database -U webgui
(enter s3cr3t as password)
set role neil;
webgui
does not need superuser
permission for this.
You want to set role
at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:
public class SetRoleJdbcInterceptor extends JdbcInterceptor {
@Override
public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication != null) {
try {
/*
use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.
Or use a whitelist-map approach
*/
String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());
Statement statement = pooledConnection.getConnection().createStatement();
statement.execute("set role \"" + username + "\"");
statement.close();
} catch(SQLException exp){
throw new RuntimeException(exp);
}
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("close".equals(method.getName())){
Statement statement = ((Connection)proxy).createStatement();
statement.execute("reset role");
statement.close();
}
return super.invoke(proxy, method, args);
}
}
How to run an awk commands in Windows?
Actually, I do like mark instruction but little differently.
I've added C:\Program Files (x86)\GnuWin32\bin\
to the Path variable,
and try to run it with type awk using cmd.
Hope it works.
Difference between save and saveAndFlush in Spring data jpa
Depending on the hibernate flush mode that you are using (AUTO
is the default) save
may or may not write your changes to the DB straight away. When you call saveAndFlush
you are enforcing the synchronization of your model state with the DB.
If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save()
and saveAndFlush()
because the select triggers a flush first. See the documention.
How would you count occurrences of a string (actually a char) within a string?
For the case of a string delimiter (not for the char case, as the subject says):
string source = "@@@once@@@upon@@@a@@@time@@@";
int count = source.Split(new[] { "@@@" }, StringSplitOptions.RemoveEmptyEntries).Length - 1;
The poster's original source value's ("/once/upon/a/time/") natural delimiter is a char '/' and responses do explain source.Split(char[]) option though...
CSS background image in :after element
As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:
background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;
Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).
No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.
Save range to variable
My use case was to save range to variable and then select it later on
Dim targetRange As Range
Set targetRange = Sheets("Sheet").Range("Name")
Application.Goto targetRange
Set targetRangeQ = Nothing ' reset
In Python, how do you convert a `datetime` object to seconds?
Maybe off-the-topic: to get UNIX/POSIX time from datetime and convert it back:
>>> import datetime, time
>>> dt = datetime.datetime(2011, 10, 21, 0, 0)
>>> s = time.mktime(dt.timetuple())
>>> s
1319148000.0
# and back
>>> datetime.datetime.fromtimestamp(s)
datetime.datetime(2011, 10, 21, 0, 0)
Note that different timezones have impact on results, e.g. my current TZ/DST returns:
>>> time.mktime(datetime.datetime(1970, 1, 1, 0, 0).timetuple())
-3600 # -1h
therefore one should consider normalizing to UTC by using UTC versions of the functions.
Note that previous result can be used to calculate UTC offset of your current timezone. In this example this is +1h, i.e. UTC+0100.
References:
auto create database in Entity Framework Core
My answer is very similar to Ricardo's answer, but I feel that my approach is a little more straightforward simply because there is so much going on in his using
function that I'm not even sure how exactly it works on a lower level.
So for those who want a simple and clean solution that creates a database for you where you know exactly what is happening under the hood, this is for you:
public Startup(IHostingEnvironment env)
{
using (var client = new TargetsContext())
{
client.Database.EnsureCreated();
}
}
This pretty much means that within the DbContext
that you created (in this case, mine is called TargetsContext
), you can use an instance of the DbContext
to ensure that the tables defined with in the class are created when Startup.cs is run in your application.
How to get the correct range to set the value to a cell?
Solution : SpreadsheetApp.getActiveSheet().getRange('F2').setValue('hello')
Explanation :
Setting value in a cell in spreadsheet to which script is attached
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);
Setting value in a cell in sheet which is open currently and to which script is attached
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(RANGE).setValue(VALUE);
Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet name known)
SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);
Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet position known)
SpreadsheetApp.openById(SHEET_ID).getSheets()[POSITION].getRange(RANGE).setValue(VALUE);
These are constants, you must define them yourself
SHEET_ID
SHEET_NAME
POSITION
VALUE
RANGE
By script attached to a sheet I mean that script is residing in the script editor of that sheet. Not attached means not residing in the script editor of that sheet. It can be in any other place.
How to read PDF files using Java?
PDFBox contains tools for text extraction.
iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.
iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.
Specified cast is not valid?
From your comment:
this line DateTime Date = reader.GetDateTime(0);
was throwing the exception
The first column is not a valid DateTime. Most likely, you have multiple columns in your table, and you're retrieving them all by running this query:
SELECT * from INFO
Replace it with a query that retrieves only the two columns you're interested in:
SELECT YOUR_DATE_COLUMN, YOUR_TIME_COLUMN from INFO
Then try reading the values again:
var Date = reader.GetDateTime(0);
var Time = reader.GetTimeSpan(1); // equivalent to time(7) from your database
Or:
var Date = Convert.ToDateTime(reader["YOUR_DATE_COLUMN"]);
var Time = (TimeSpan)reader["YOUR_TIME_COLUMN"];
Git merge is not possible because I have unmerged files
I repeatedly had the same challenge sometime ago. This problem occurs mostly when you are trying to pull from the remote repository and you have some files on your local instance conflicting with the remote version, if you are using git from an IDE such as IntelliJ, you will be prompted and allowed to make a choice if you want to retain your own changes or you prefer the changes in the remote version to overwrite yours'. If you don't make any choice then you fall into this conflict. all you need to do is run:
git merge --abort # The unresolved conflict will be cleared off
And you can continue what you were doing before the break.
When using a Settings.settings file in .NET, where is the config actually stored?
Assuming that you're talking about desktop and not web applications:
When you add settings to a project, VS creates a file named app.config
in your project directory and stores the settings in that file. It also builds the Settings.cs
file that provides the static accessors to the individual settings.
At compile time, VS will (by default; you can change this) copy the app.config
to the build directory, changing its name to match the executable (e.g. if your executable is named foo.exe
, the file will be named foo.exe.config
), which is the name the .NET configuration manager looks for when it retrieves settings at runtime.
If you change a setting through the VS settings editor, it will update both app.config
and Settings.cs
. (If you look at the property accessors in the generated code in Settings.cs
, you'll see that they're marked with an attribute containing the default value of the setting that's in your app.config
file.) If you change a setting by editing the app.config
file directly, Settings.cs
won't be updated, but the new value will still be used by your program when you run it, because app.config
gets copied to foo.exe.config
at compile time. If you turn this off (by setting the file's properties), you can change a setting by directly editing the foo.exe.config
file in the build directory.
Then there are user-scoped settings.
Application-scope settings are read-only. Your program can modify and save user-scope settings, thus allowing each user to have his/her own settings. These settings aren't stored in the foo.exe.config
file (since under Vista, at least, programs can't write to any subdirectory of Program Files
without elevation); they're stored in a configuration file in the user's application data directory.
The path to that file is %appdata%\%publisher_name%\%program_name%\%version%\user.config
, e.g. C:\Users\My Name\AppData\Local\My_Company\My_Program.exe\1.0.0\user.config
. Note that if you've given your program a strong name, the strong name will be appended to the program name in this path.
How to return value from Action()?
You can also take advantage of the fact that a lambda or anonymous method can close over variables in its enclosing scope.
MyType result;
SimpleUsing.DoUsing(db =>
{
result = db.SomeQuery(); //whatever returns the MyType result
});
//do something with result
Rails :include vs. :joins
.joins
will just joins the tables and brings selected fields in return. if you call associations on joins query result, it will fire database queries again
:includes
will eager load the included associations and add them in memory. :includes
loads all the included tables attributes. If you call associations on include query result, it will not fire any queries
File tree view in Notepad++
You can also use you own computer built-in functions:
- Create a file, write this on it:
tree /a /f >tree.txt
- Save the file as
any_name_you_want.BAT
- Launch it, it will create a file named
tree.txt
that contains you directory TREE.
Best way to make a shell script daemon?
It really depends on what is the binary itself going to do.
For example I want to create some listener.
The starting Daemon is simple task :
lis_deamon :
#!/bin/bash
# We will start the listener as Deamon process
#
LISTENER_BIN=/tmp/deamon_test/listener
test -x $LISTENER_BIN || exit 5
PIDFILE=/tmp/deamon_test/listener.pid
case "$1" in
start)
echo -n "Starting Listener Deamon .... "
startproc -f -p $PIDFILE $LISTENER_BIN
echo "running"
;;
*)
echo "Usage: $0 start"
exit 1
;;
esac
this is how we start the daemon (common way for all /etc/init.d/ staff)
now as for the listener it self,
It must be some kind of loop/alert or else that will trigger the script
to do what u want. For example if u want your script to sleep 10 min
and wake up and ask you how you are doing u will do this with the
while true ; do sleep 600 ; echo "How are u ? " ; done
Here is the simple listener that u can do that will listen for your
commands from remote machine and execute them on local :
listener :
#!/bin/bash
# Starting listener on some port
# we will run it as deamon and we will send commands to it.
#
IP=$(hostname --ip-address)
PORT=1024
FILE=/tmp/backpipe
count=0
while [ -a $FILE ] ; do #If file exis I assume that it used by other program
FILE=$FILE.$count
count=$(($count + 1))
done
# Now we know that such file do not exist,
# U can write down in deamon it self the remove for those files
# or in different part of program
mknod $FILE p
while true ; do
netcat -l -s $IP -p $PORT < $FILE |/bin/bash > $FILE
done
rm $FILE
So to start UP it : /tmp/deamon_test/listener start
and to send commands from shell (or wrap it to script) :
test_host#netcat 10.184.200.22 1024
uptime
20:01pm up 21 days 5:10, 44 users, load average: 0.62, 0.61, 0.60
date
Tue Jan 28 20:02:00 IST 2014
punt! (Cntrl+C)
Hope this will help.
Setting individual axis limits with facet_wrap and scales = "free" in ggplot2
I am not sure I understand what you want, but based on what I understood
the x scale seems to be the same, it is the y scale that is not the same, and that is because you specified scales ="free"
you can specify scales = "free_x" to only allow x to be free (in this case it is the same as pred has the same range by definition)
p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free_x")
worked for me, see the picture
I think you were making it too difficult - I do seem to remember one time defining the limits based on a formula with min and max and if faceted I think it used only those values, but I can't find the code
How to limit text width
Try
<div style="max-width:200px; word-wrap:break-word;">Texttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt</div>
What is the difference between bottom-up and top-down?
Following is the DP based solution for Edit Distance problem which is top down. I hope it will also help in understanding the world of Dynamic Programming:
public int minDistance(String word1, String word2) {//Standard dynamic programming puzzle.
int m = word2.length();
int n = word1.length();
if(m == 0) // Cannot miss the corner cases !
return n;
if(n == 0)
return m;
int[][] DP = new int[n + 1][m + 1];
for(int j =1 ; j <= m; j++) {
DP[0][j] = j;
}
for(int i =1 ; i <= n; i++) {
DP[i][0] = i;
}
for(int i =1 ; i <= n; i++) {
for(int j =1 ; j <= m; j++) {
if(word1.charAt(i - 1) == word2.charAt(j - 1))
DP[i][j] = DP[i-1][j-1];
else
DP[i][j] = Math.min(Math.min(DP[i-1][j], DP[i][j-1]), DP[i-1][j-1]) + 1; // Main idea is this.
}
}
return DP[n][m];
}
You can think of its recursive implementation at your home. It's quite good and challenging if you haven't solved something like this before.
correct way to use super (argument passing)
As explained in Python's super() considered super, one way is to have class eat the arguments it requires, and pass the rest on. Thus, when the call-chain reaches object
, all arguments have been eaten, and object.__init__
will be called without arguments (as it expects). So your code should look like this:
class A(object):
def __init__(self, *args, **kwargs):
print "A"
super(A, self).__init__(*args, **kwargs)
class B(object):
def __init__(self, *args, **kwargs):
print "B"
super(B, self).__init__(*args, **kwargs)
class C(A):
def __init__(self, arg, *args, **kwargs):
print "C","arg=",arg
super(C, self).__init__(*args, **kwargs)
class D(B):
def __init__(self, arg, *args, **kwargs):
print "D", "arg=",arg
super(D, self).__init__(*args, **kwargs)
class E(C,D):
def __init__(self, arg, *args, **kwargs):
print "E", "arg=",arg
super(E, self).__init__(*args, **kwargs)
print "MRO:", [x.__name__ for x in E.__mro__]
E(10, 20, 30)
What do the makefile symbols $@ and $< mean?
in exemple if you want to compile sources but have objects in an different directory :
You need to do :
gcc -c -o <obj/1.o> <srcs/1.c> <obj/2.o> <srcs/2.c> ...
but with most of macros the result will be all objects followed by all sources, like :
gcc -c -o <all OBJ path> <all SRC path>
so this will not compile anything ^^ and you will not be able to put your objects files in a different dir :(
the solution is to use these special macros
$@ $<
this will generate a .o file (obj/file.o) for each .c file in SRC (src/file.c)
$(OBJ):$(SRC)
gcc -c -o $@ $< $(HEADERS) $(FLAGS)
it means :
$@ = $(OBJ)
$< = $(SRC)
but lines by lines INSTEAD of all lines of OBJ followed by all lines of SRC
Vim multiline editing like in sublimetext?
There are several ways to accomplish that in Vim. I don't know which are most
similar to Sublime Text's though.
The first one would be via multiline insert mode. Put your cursor to the
second "a" in the first line, press Ctrl-V
, select all lines, then press I
, and
put in a doublequote. Pressing <esc>
will repeat the operation on every line.
The second one is via macros. Put the cursor on the first character, and start
recording a macro with qa
.
Go the your right with llll
, enter insert mode with
a
, put down a doublequote, exit insert mode, and go back to the beginning of
your row with <home>
(or equivalent). Press j
to move down one row.
Stop recording with q
.
And then replay the macro with @a
. Several times.
Does any of the above approaches work for you?
JPA Hibernate One-to-One relationship
I think you still need the primary key property in the OtherInfo class.
@Entity
public class OtherInfo {
@Id
public int id;
@OneToOne(mappedBy="otherInfo")
public Person person;
rest of attributes ...
}
Also, you may need to add the @PrimaryKeyJoinColumn annotation to the other side of the mapping. I know that Hibernate uses this by default. But then I haven't used JPA annotations, which seem to require you to specify how the association wokrs.
Creating a generic method in C#
Convert.ChangeType()
doesn't correctly handle nullable types or enumerations in .NET 2.0 BCL (I think it's fixed for BCL 4.0 though). Rather than make the outer implementation more complex, make the converter do more work for you. Here's an implementation I use:
public static class Converter
{
public static T ConvertTo<T>(object value)
{
return ConvertTo(value, default(T));
}
public static T ConvertTo<T>(object value, T defaultValue)
{
if (value == DBNull.Value)
{
return defaultValue;
}
return (T) ChangeType(value, typeof(T));
}
public static object ChangeType(object value, Type conversionType)
{
if (conversionType == null)
{
throw new ArgumentNullException("conversionType");
}
// if it's not a nullable type, just pass through the parameters to Convert.ChangeType
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
// null input returns null output regardless of base type
if (value == null)
{
return null;
}
// it's a nullable type, and not null, which means it can be converted to its underlying type,
// so overwrite the passed-in conversion type with this underlying type
conversionType = Nullable.GetUnderlyingType(conversionType);
}
else if (conversionType.IsEnum)
{
// strings require Parse method
if (value is string)
{
return Enum.Parse(conversionType, (string) value);
}
// primitive types can be instantiated using ToObject
else if (value is int || value is uint || value is short || value is ushort ||
value is byte || value is sbyte || value is long || value is ulong)
{
return Enum.ToObject(conversionType, value);
}
else
{
throw new ArgumentException(String.Format("Value cannot be converted to {0} - current type is " +
"not supported for enum conversions.", conversionType.FullName));
}
}
return Convert.ChangeType(value, conversionType);
}
}
Then your implementation of GetQueryString<T> can be:
public static T GetQueryString<T>(string key)
{
T result = default(T);
string value = HttpContext.Current.Request.QueryString[key];
if (!String.IsNullOrEmpty(value))
{
try
{
result = Converter.ConvertTo<T>(value);
}
catch
{
//Could not convert. Pass back default value...
result = default(T);
}
}
return result;
}
Upgrade version of Pandas
Simple Solution, just type the below:
conda update pandas
Type this in your preferred shell (on Windows, use Anaconda Prompt as administrator).
How to select into a variable in PL/SQL when the result might be null?
Using an Cursor FOR LOOP Statement is my favourite way to do this.
It is safer than using an explicit cursor, because you don't need to remember to close it, so you can't "leak" cursors.
You don't need "into" variables, you don't need to "FETCH", you don't need to catch and handle "NO DATA FOUND" exceptions.
Try it, you'll never go back.
v_column my_table.column%TYPE;
v_column := null;
FOR rMyTable IN (SELECT COLUMN FROM MY_TABLE WHERE ....) LOOP
v_column := rMyTable.COLUMN;
EXIT; -- Exit the loop if you only want the first result.
END LOOP;
Numpy: Checking if a value is NaT
pandas can check for NaT
with pandas.isnull
:
>>> import numpy as np
>>> import pandas as pd
>>> pd.isnull(np.datetime64('NaT'))
True
If you don't want to use pandas you can also define your own function (parts are taken from the pandas source):
nat_as_integer = np.datetime64('NAT').view('i8')
def isnat(your_datetime):
dtype_string = str(your_datetime.dtype)
if 'datetime64' in dtype_string or 'timedelta64' in dtype_string:
return your_datetime.view('i8') == nat_as_integer
return False # it can't be a NaT if it's not a dateime
This correctly identifies NaT values:
>>> isnat(np.datetime64('NAT'))
True
>>> isnat(np.timedelta64('NAT'))
True
And realizes if it's not a datetime or timedelta:
>>> isnat(np.timedelta64('NAT').view('i8'))
False
In the future there might be an isnat
-function in the numpy code, at least they have a (currently open) pull request about it: Link to the PR (NumPy github)
How to set image on QPushButton?
What you can do is use a pixmap as an icon and then put this icon onto the button.
To make sure the size of the button will be correct, you have to reisze the icon according to the pixmap size.
Something like this should work :
QPixmap pixmap("image_path");
QIcon ButtonIcon(pixmap);
button->setIcon(ButtonIcon);
button->setIconSize(pixmap.rect().size());
finding multiples of a number in Python
Based on mathematical concepts, I understand that:
- all natural numbers that, divided by
n
, having 0
as remainder, are all multiples of n
Therefore, the following calculation also applies as a solution (multiples between 1 and 100):
>>> multiples_5 = [n for n in range(1, 101) if n % 5 == 0]
>>> multiples_5
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
For further reading:
pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/
C:\Users\Asus>pip install matplotlib
Downloading/unpacking matplotlib
Cannot fetch index base URL https://pypi.python.org/simple/
Could not find any downloads that satisfy the requirement matplotlib
Cleaning up...
No distributions at all found for matplotlib
Storing debug log for failure in C:\Users\Asus\pip\pip.log
I used 'easy_install pip==1.2.1' and it worked fine.
C:\Users\Asus>easy_install pip==1.2.1
Searching for pip==1.2.1
Reading https://pypi.python.org/simple/pip/
Best match: pip 1.2.1
Downloading ...
Then on using this command 'pip install matplotlib'
C:\Users\Asus>pip install matplotlib
Downloading/unpacking matplotlib
Downloading matplotlib-2.0.0b4.tar.gz (unknown size):
Get integer value from string in swift
above answer didnt help me as my string value was "700.00"
with Swift 2.2 this works for me
let myString = "700.00"
let myInt = (myString as NSString).integerValue
I passed myInt to NSFormatterClass
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.maximumFractionDigits = 0
let priceValue = formatter.stringFromNumber(myInt!)!
//Now priceValue is ? 700
Thanks to this blog post.