_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d12301 | train | If you change your setup to
tiles = []
for row in range(0,3):
tiles.append([])
for column in range(0,3):
tiles[-1].append(Tile())
tiles[-1][-1].grid(row, column)
you can access your tiles as tiles[row][column] at the end and get the text to compare against the win conditions. | unknown | |
d12302 | train | You were nearly there: Just use n() instead of sum(Ticket) to count the number of rows:
library(dplyr)
library(lubridate)
data %>%
mutate(Created = dmy(Created)) %>%
group_by(month = floor_date(Created, "month")) %>%
summarize(amount = n())
# A tibble: 2 x 2
month amount
<date> <int>
1 2019-01-01 19
2 2019-02-01 4
However, there is a shortcut which uses count():
data %>%
count(CreatedMonth = dmy(Created) %>% floor_date("month"))
# A tibble: 2 x 2
CreatedMonth n
<date> <int>
1 2019-01-01 19
2 2019-02-01 4
For the sake of completeness, here is also a data.table version:
library(lubridate)
library(data.table)
setDT(data)[, .N, by = .(CreatedMonth = floor_date(dmy(Created), "month"))]
CreatedMonth N
1: 2019-01-01 19
2: 2019-02-01 4
Data
data <- readr::read_table("Created Ticket
01-Jan-19 a1
02-Jan-19 a2
03-Jan-19 a3
04-Jan-19 a4
05-Jan-19 a5
06-Jan-19 a6
07-Jan-19 a7
08-Jan-19 a8
09-Jan-19 a9
10-Jan-19 a10
11-Jan-19 a11
12-Jan-19 a12
13-Jan-19 a13
14-Jan-19 a14
15-Jan-19 a15
16-Jan-19 a16
17-Jan-19 a17
18-Jan-19 a18
19-Jan-19 a19
01-Feb-19 a20
02-Feb-19 a21
03-Feb-19 a22
04-Feb-19 a23")
A: Using dplyr we can first convert Created column to actual Date and group them by each month and count number of tickets for each group.
library(dplyr)
df %>%
mutate(Created = as.Date(Created, "%d-%b-%y")) %>%
arrange(Created) %>%
mutate(Yearmon = format(Created, "%B-%Y"),
Yearmon = factor(Yearmon, levels = unique(Yearmon))) %>%
group_by(Yearmon) %>%
summarise(count = n())
# Yearmon count
# <fct> <int>
#1 January-2019 19
#2 February-2019 4 | unknown | |
d12303 | train | Adding to Jon Skeet's answer, if you want to guarantee that a new thread is created every time, you can write your own TaskScheduler that creates a new thread.
A: Try this:
var taskCompletionSource = new TaskCompletionSource<bool>();
Thread t = new Thread(() =>
{
try
{
Operation();
taskCompletionSource.TrySetResult(true);
}
catch (Exception e)
{
taskCompletionSource.TrySetException(e);
}
});
void Operation()
{
// Some work in thread
}
t.Start();
await taskCompletionSource.Task;
You also can write extension methods for Action, Func and so on.
For example:
public static Task RunInThread(
this Action action,
Action<Thread> initThreadAction = null)
{
TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
Thread thread = new Thread(() =>
{
try
{
action();
taskCompletionSource.TrySetResult(true);
}
catch (Exception e)
{
taskCompletionSource.TrySetException(e);
}
});
initThreadAction?.Invoke(thread);
thread.Start();
return taskCompletionSource.Task;
}
or
public static Task<TResult> RunInThread<T1, T2, TResult>(
this Func<T1, T2, TResult> function,
T1 param1,
T2 param2,
Action<Thread> initThreadAction = null)
{
TaskCompletionSource<TResult> taskCompletionSource = new TaskCompletionSource<TResult>();
Thread thread = new Thread(() =>
{
try
{
TResult result = function(param1, param2);
taskCompletionSource.TrySetResult(result);
}
catch (Exception e)
{
taskCompletionSource.TrySetException(e);
}
});
initThreadAction?.Invoke(thread);
thread.Start();
return taskCompletionSource.Task;
}
and use it like that:
var result = await some_function.RunInThread(param1, param2).ConfigureAwait(true);
A: Hello and thank you all for the answers. You all got +1. All suggested solution did not work for my case. The problem is that when you sleep a thread it will be reused at some point of time. The people above suggested:
*
*using LongRunning => This will not work if you have nested/child
tasks
*custom task scheduler => I tried to write my own and also tried this
ThreadPerTaskScheduler which also di not work.
*using pure threads => Still failing...
*you could also check this project at Multithreading.Scheduler github
My solution
I don't like it but it works. Basically I block the thread so it cannot be reused. Bellow are the extension methods and a working example. Again, thank you.
https://gist.github.com/4150635
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication
{
public static class ThreadExtensions
{
/// <summary>
/// Blocks the current thread for a period of time so that the thread cannot be reused by the threadpool.
/// </summary>
public static void Block(this Thread thread, int millisecondsTimeout)
{
new WakeSleepClass(millisecondsTimeout).SleepThread();
}
/// <summary>
/// Blocks the current thread so that the thread cannot be reused by the threadpool.
/// </summary>
public static void Block(this Thread thread)
{
new WakeSleepClass().SleepThread();
}
/// <summary>
/// Blocks the current thread for a period of time so that the thread cannot be reused by the threadpool.
/// </summary>
public static void Block(this Thread thread, TimeSpan timeout)
{
new WakeSleepClass(timeout).SleepThread();
}
class WakeSleepClass
{
bool locked = true;
readonly TimerDisposer timerDisposer = new TimerDisposer();
public WakeSleepClass(int sleepTime)
{
var timer = new Timer(WakeThread, timerDisposer, sleepTime, sleepTime);
timerDisposer.InternalTimer = timer;
}
public WakeSleepClass(TimeSpan sleepTime)
{
var timer = new Timer(WakeThread, timerDisposer, sleepTime, sleepTime);
timerDisposer.InternalTimer = timer;
}
public WakeSleepClass()
{
var timer = new Timer(WakeThread, timerDisposer, Timeout.Infinite, Timeout.Infinite);
timerDisposer.InternalTimer = timer;
}
public void SleepThread()
{
while (locked)
lock (timerDisposer) Monitor.Wait(timerDisposer);
locked = true;
}
public void WakeThread(object key)
{
locked = false;
lock (key) Monitor.Pulse(key);
((TimerDisposer)key).InternalTimer.Dispose();
}
class TimerDisposer
{
public Timer InternalTimer { get; set; }
}
}
}
class Program
{
private static readonly Queue<CancellationTokenSource> tokenSourceQueue = new Queue<CancellationTokenSource>();
static void Main(string[] args)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
tokenSourceQueue.Enqueue(tokenSource);
ConcurrentDictionary<int, int> startedThreads = new ConcurrentDictionary<int, int>();
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);
Task.Factory.StartNew(() =>
{
startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, (a, b) => b);
for (int j = 0; j < 50; j++)
Task.Factory.StartNew(() => startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, (a, b) => b));
for (int j = 0; j < 50; j++)
{
Task.Factory.StartNew(() =>
{
while (!tokenSource.Token.IsCancellationRequested)
{
if (startedThreads.ContainsKey(Thread.CurrentThread.ManagedThreadId)) Console.WriteLine("Thread reused");
Thread.CurrentThread.Block(10);
if (startedThreads.ContainsKey(Thread.CurrentThread.ManagedThreadId)) Console.WriteLine("Thread reused");
}
}, tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default)
.ContinueWith(task =>
{
WriteExceptions(task.Exception);
Console.WriteLine("-----------------------------");
}, TaskContinuationOptions.OnlyOnFaulted);
}
Thread.CurrentThread.Block();
}, tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default)
.ContinueWith(task =>
{
WriteExceptions(task.Exception);
Console.WriteLine("-----------------------------");
}, TaskContinuationOptions.OnlyOnFaulted);
}
Console.Read();
}
private static void WriteExceptions(Exception ex)
{
Console.WriteLine(ex.Message);
if (ex.InnerException != null)
WriteExceptions(ex.InnerException);
}
}
}
A: If you specify TaskCreationOptions.LongRunning when starting the task, that provides a hint to the scheduler, which the default scheduler takes as an indicator to create a new thread for the task.
It's only a hint - I'm not sure I'd rely on it... but I haven't seen any counterexamples using the default scheduler.
A: Just start threads with new Thread() and then Start() them
static void Main(string[] args)
{
ConcurrentDictionary<int, int> startedThreads = new ConcurrentDictionary<int, int>();
for (int i = 0; i < 10; i++)
{
new Thread(() =>
{
new Thread(() =>
{
startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, (a, b) => b);
}).Start();
for (int j = 0; j < 100; j++)
{
new Thread(() =>
{
while (true)
{
Thread.Sleep(10);
if (startedThreads.ContainsKey(Thread.CurrentThread.ManagedThreadId))
Console.WriteLine("Thread reused");
}
}).Start();
}
}).Start();
}
Console.Read();
}
Tasks are supposed to be managed by the scheduler. The whole idea of Tasks is that the runtime will decide when a new thread is needed. On the other hand if you do need different threads chances are something else in the code is wrong like overdependency on Thread.Sleep() or thread local storage.
As pointed out you can create your own TaskScheduler and use tasks to create threads but then why use Tasks to begin with?
A: Here is a custom TaskScheduler that executes the tasks on a dedicated thread per task:
public class ThreadPerTask_TaskScheduler : TaskScheduler
{
protected override void QueueTask(Task task)
{
var thread = new Thread(() => TryExecuteTask(task));
thread.IsBackground = true;
thread.Start();
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
return TryExecuteTask(task);
}
protected override IEnumerable<Task> GetScheduledTasks() { yield break; }
}
Usage example:
var parallelOptions = new ParallelOptions()
{
MaxDegreeOfParallelism = 3,
TaskScheduler = new ThreadPerTask_TaskScheduler()
};
Parallel.ForEach(Enumerable.Range(1, 10), parallelOptions, item =>
{
Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}" +
$" [{Thread.CurrentThread.ManagedThreadId}]" +
$" Processing #{item}" +
(Thread.CurrentThread.IsBackground ? ", Background" : "") +
(Thread.CurrentThread.IsThreadPoolThread ? ", ThreadPool" : ""));
Thread.Sleep(1000); // Simulate CPU-bound work
});
Output:
20:38:56.770 [4] Processing #3, Background
20:38:56.770 [5] Processing #2, Background
20:38:56.770 [1] Processing #1
20:38:57.782 [1] Processing #4
20:38:57.783 [8] Processing #5, Background
20:38:57.783 [7] Processing #6, Background
20:38:58.783 [1] Processing #7
20:38:58.783 [10] Processing #8, Background
20:38:58.787 [9] Processing #9, Background
20:38:59.783 [1] Processing #10
Try it on Fiddle.
This custom TaskScheduler allows the current thread to participate in the computations too. This is demonstrated in the above example by the thread [1] processing the items #1, #4, #7 and #10. If you don't want this to happen, just replace the code inside the TryExecuteTaskInline with return false;.
Another example, featuring the Task.Factory.StartNew method. Starting 100 tasks on 100 different threads:
var oneThreadPerTask = new ThreadPerTask_TaskScheduler();
Task[] tasks = Enumerable.Range(1, 100).Select(_ =>
{
return Task.Factory.StartNew(() =>
{
Thread.Sleep(1000); // Simulate long-running work
}, default, TaskCreationOptions.None, oneThreadPerTask);
}).ToArray();
In this case the current thread is not participating in the work, because all tasks are started behind the scenes by invoking their Start method, and not the
RunSynchronously. | unknown | |
d12304 | train | This doesn't seem to be well documented. As I read "How Files are Referenced" in the "Xcode Project Management Guide":
*
*If the file is in the project's folder, you get a reference relative to an enclosing group.
*If the file is created by one of the targets, you get a reference relative to the build product.
*Otherwise, I think, you get an absolute path.
A: By default - Eclosing-Group*.
*Beginning Xcode (James Bucanek) Chapter 5, p.76 | unknown | |
d12305 | train | You need to add vendor specific values for transform and transition properties. Below is the modified CSS:
$headerColour: #456878; $headerHeight: 58px; $headerLineHeight: $headerHeight - 2px; @import url(http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900); .cf:after {
clear: both;
content: " ";
display: table;
}
body {
background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/12596/bg.png");
background-attachment: fixed;
-ms-background-size: contain;
background-size: contain;
color: #fff;
font-family: "Lato";
font-size: 18px;
font-weight: 300;
overflow-y: scroll;
}
header {
background: $headerColour;
height: $headerHeight;
position: relative;
}
header li {
position: absolute;
top: 0;
line-height: $headerLineHeight;
}
header li.logo {
left: 20px;
}
header li.user {
right: 20px;
}
.wrapper {
position: absolute;
top: 120px;
left: 0;
right: 0;
margin: auto;
width: 80%;
}
nav {
margin-bottom: 50px;
margin-left: 20px;
}
nav li {
color: rgba(255, 255, 255, 0.75);
cursor: pointer;
float: left;
font-size: 20px;
margin-right: 60px;
-webkit-transition: color 500ms ease 0s;
-moz-transition: color 500ms ease 0s;
-ms-transition: color 500ms ease 0s;
-o-transition: color 500ms ease 0s;
transition: color 500ms ease 0s;
width: 100px;
}
nav li:not(.active):hover,
nav li.active {
color: rgba(255, 255, 255, 1);
}
nav li.active {
font-size: 22px;
font-weight: 400;
}
.tab-content .tab {
position: absolute;
margin-bottom: 100px;
visibility: hidden;
}
.tab-content .tab.active {
visibility: visible;
}
.tab-content .tab > ul {
margin-bottom: 100px;
}
.tab-content .tab li {
background: #fff;
height: 200px;
width: 200px;
float: left;
background: #fff;
margin: 20px;
-ms-border-radius: 30px;
border-radius: 30px;
-ms-opacity: 0;
opacity: 0;
-webkit-transform: translatey(-50px) scale(0);
-moz-transform: translatey(-50px) scale(0);
-ms-transform: translatey(-50px) scale(0);
-o-transform: translatey(-50px) scale(0);
transform: translatey(-50px) scale(0);
}
.tab-content .tab.active li {
-webkit-transition: all 500ms ease;
-moz-transition: all 500ms ease;
-ms-transition: all 500ms ease;
-o-transition: all 500ms ease;
transition: all 500ms ease;
-webkit-transform-origin: top center;
-moz-transform-origin: top center;
-ms-transform-origin: top center;
-o-transform-origin: top center;
transform-origin: top center;
-webkit-transform: translatey(0) scale(1);
-moz-transform: translatey(0) scale(1);
-ms-transform: translatey(0) scale(1);
-o-transform: translatey(0) scale(1);
transform: translatey(0) scale(1);
-ms-opacity: 1;
opacity: 1;
}
@for $i from 1 through 50 {
.tab-content .tab.active li:nth-child(#{$i}) {
transition-delay: (#{$i * 0.1}s);
}
}
Code Pen: http://codepen.io/anon/pen/gIDsv | unknown | |
d12306 | train | To clone a repository means that you will download the whole code of the repository to your laptop.
A fork is a copy of a repository. Forking a repository allows you to freely experiment with changes without affecting the original project.
Most commonly, forks are used to either propose changes to someone else's project or to use someone else's project as a starting point for your own idea. More at Fork A Repo.
as @TimBiegeleisen says, you can get the project and stay updated by clone once then git fetch it periodically.
For example, if you want to cloning POX Controller, clone it:
git clone https://github.com/noxrepo/pox
Then to update it, do the following command on your cloned project:
cd pox // go to your clone project
git fetch
Or you can use git pull instead of git fetch if only need to stay update without keeping your change in the cloned project.
But you must remember the difference between git fetch and git pull. @GregHewgill answers explain it in details:
In the simplest terms, git pull does a git fetch followed by a git merge.
You can do a git fetch at any time to update your remote-tracking branches under refs/remotes/<remote>/. This operation never changes any of your own local branches under refs/heads, and is safe to do without changing your working copy. I have even heard of people running git fetch periodically in a cron job in the background (although I wouldn't recommend doing this).
A git pull is what you would do to bring a local branch up-to-date with its remote version, while also updating your other remote-tracking branches.
Git documentation: git pull | unknown | |
d12307 | train | As the php container uses supervisor you can add another application to the config. Reference for the config can be found here.
Example
ssh.ini:
[program:sshd]
command=/usr/sbin/sshd -D | unknown | |
d12308 | train | Make sure you handle the OPTIONS request in the server. If it returns 404 then Firefox wont call the next request (in your case the POST mentioned above).
A: Try this with last version of AngularJS:
$http.post("http://0.0.0.0:4567/authenticate", {
Lusername: $scope.Lusername,
Lpassword: $scope.Lpassword
}).success(function(data, status, headers, config) {
alert("Success");
}); | unknown | |
d12309 | train | Did you mean sometimes the Ajax called more than one time, in that case you can busy flag. By default the busy flag set to false. Here is the code to do that
var busy = false;
if(($(window).scrollTop() + $(window).height() == $(document).height()) && (isload=='true'))
{
if(busy)
return;
busy = true;
$('#loading').show();
$.ajax({
url: 'aaa.php',
type: 'POST',
data: $('#fid').serialize(),
cache: false,
success: function(response)
{
$('#demoajax').find('.nextpage').remove();
$('#demoajax').find('.isload').remove();
$("#loading").fadeOut("slow");
$('#demoajax').append(response);
},
complete: function()
{
busy = false;
}
});
}
return false;
});
});
I think this should solve the problem.
Thank You. | unknown | |
d12310 | train | Running the command that way works only when connection is done through psql.
A: You can do the following in psql.
SELECT 1 as one, 2 as two \g /tmp/1.csv
then in psql
\! cat /tmp/1.csv
or you can
copy (SELECT 1 as one, 2 as two) to '/tmp/1.csv' with (format csv , delimiter '|');
But You can't STDOUT and filename. Because in manual(https://www.postgresql.org/docs/current/sql-copy.html):
COPY { table_name [ ( column_name [, ...] ) ] | ( query ) }
TO { 'filename' | PROGRAM 'command' | STDOUT }
[ [ WITH ] ( option [, ...] ) ]
the Vertical line | means: you must choose one alternative.(source: https://www.postgresql.org/docs/14/notation.html) | unknown | |
d12311 | train | That looks like protobuf-net; fortunately, the library includes a tool to spit out the .proto schema for what it thinks of your model:
var schema = Serializer.GetProto<TickRecord>();
which comes out as:
message TickRecord {
required bcl.DateTime DT = 1;
required double BidPrice = 2 [default = 0];
required double AskPrice = 3 [default = 0];
required sfixed32 BidSize = 4 [default = 0];
required sfixed32 AskSize = 5 [default = 0];
}
where bcl.DateTime is a protobuf-net complex data type described in "bcl.proto".
Frankly, I suggest changing your date-time to a long using unix time - it'll make things a lot simpler here. That gives you:
message TickRecord {
required sfixed64 DT = 1 [default = 0];
required double BidPrice = 2 [default = 0];
required double AskPrice = 3 [default = 0];
required sfixed32 BidSize = 4 [default = 0];
required sfixed32 AskSize = 5 [default = 0];
}
which you can give to your colleague, and they can run protoc or whatever other platform/library tool they need for protocol buffers in their environment, and they should be set. The serialization format is intentionally cross-platform, so the data should work fine.
Note: *WithLengthPrefix works by wrapping the data in an outer shell. I need to see the exact parameters you are using to advise on how to advise your colleague.
Note: changing the DateTime to long is a breaking change; if you can't do that your colleague will have to look at bcl.proto (just Google it) and translate it into python. | unknown | |
d12312 | train | This is how I solved it
new_samples = np.array([test_data[8]], dtype=float)
y = list(classifier.predict(new_samples, as_iterable=True))
print('Predictions: {}'.format(str(y)))
print ("Predicted %s, Label: %d" % (str(y), test_labels[8]))
A: No tensorflow here, so let's mock up a generator and test it against your print expression
In [11]: def predict(a, b):
...: for i in range(10):
...: yield i, i*i
...:
In [12]: print('a:%d, b:%d'%(predict(0, 0)))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-29ec761936ef> in <module>()
----> 1 print('a:%d, b:%d'%(predict(0, 0)))
TypeError: %d format: a number is required, not generator
So far, so good: I have the same problem that you've experienced.
The problem is, of course, that what you get when you call a generator function are not values but a generator object...
You have to iterate on the generator objects, using whatever is returned from each iteration, e.g.,
In [13]: print('\n'.join('a:%d, b:%d'%(i,j) for i, j in predict(0,0)))
a:0, b:0
a:1, b:1
a:2, b:4
a:3, b:9
a:4, b:16
a:5, b:25
a:6, b:36
a:7, b:49
a:8, b:64
a:9, b:81
or, if you don't like one-liners,
In [14]: for i, j in predict(0, 0):
...: print('a:%d, b:%d'%(i,j))
...:
a:0, b:0
a:1, b:1
a:2, b:4
a:3, b:9
a:4, b:16
a:5, b:25
a:6, b:36
a:7, b:49
a:8, b:64
a:9, b:81
In other words, you have to explicitly consume what the generator is producing.
A: From the documentation:
Runs inference to determine the class probability predictions.
(deprecated arguments)
SOME ARGUMENTS ARE DEPRECATED. They will be removed after 2016-09-15.
Instructions for updating: The default behavior of predict() is
changing. The default value for as_iterable will change to True, and
then the flag will be removed altogether. The behavior of this flag is
described below.
Try:
classifier.predict(x=test_data[0]) | unknown | |
d12313 | train | There is one synchronization object in .NET that isn't re-entrant, you are looking for a Semaphore.
Before you commit to this, do get your ducks in a row and ask yourself how it can be possible that BeginProcess() can be called again on the same thread. That is very, very unusual, your code has to be re-entrant for that to happen. This can normally only happen on a thread that has a dispatcher loop, the UI thread of a GUI app is a common example. If this is truly possible and you actually use a Semaphore then you'll get to deal with the consequence as well, your code will deadlock. Since it recursed into BeginProcess and stalls on the semaphore. Thus never completing and never able to call EndProcess(). There's a good reason why Monitor and Mutex are re-entrant :)
A: You can use Semaphore class which came with .NET Framework 2.0.
A good usage of Semaphores is to synchronize limited amount of resources. In your case it seems you have resources like Context which you want to share between consumers.
You can create a semaphore to manage the resources like:
var resourceManager = new Semaphore(0, 10);
And then wait for a resource to be available in the BeginProcess method using:
resourceManager.WaitOne();
And finally free the resource in the EndProcess method using:
resourceManager.Release();
Here's a good blog about using Semaphores in a situation like yours:
https://web.archive.org/web/20121207180440/http://www.dijksterhuis.org/using-semaphores-in-c/
A: There is very simple way to prevent re-entrancy (on one thread):
private bool bRefresh = false;
private void Refresh()
{
if (bRefresh) return;
bRefresh = true;
try
{
// do something here
}
finally
{
bRefresh = false;
}
}
A: The Interlocked class can be used for a thread-safe solution that exits the method, instead of blocking when a re-entrant call is made. Like Vlad Gonchar solution, but thread-safe.
private int refreshCount = 0;
private void Refresh()
{
if (Interlocked.Increment(ref refreshCount) != 1) return;
try
{
// do something here
}
finally
{
Interlocked.Decrement(ref refreshCount);
}
} | unknown | |
d12314 | train | You are missing one of the variables:
The string should be :
https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_cart&[email protected]&invoice=1949¤cy_code=USD&item_name=localhost&item_number=1&quantity=1&amount=100.00&return=http://localhost/drupal/user/register&cancel_return=http://localhost/drupal/paypal/cancel&add=1
add=1 is missing
Check the variables associated with cart command here | unknown | |
d12315 | train | Try to use id instead class to refer in jQuery, leave the classes for CSS.
Check it here http://jsfiddle.net/hbzqnrm8/5/
I hope it helps you.
<button id="attack_enabled">ATTACK</button>
<button id="restore_enabled">RESTORE</button>
<div class="territory_middle_complete">ADD A CLASS HERE</div>
I've edited your jQuery code, and add what I think you want to achieve. Of course if you want to check the existance of the cookie when clicking the "restore" button, if not, just move the if condition wherever you needed, but not outside the click function, because it will be executed only on loading the file.
$("#attack_enabled").click(function(){
createCookie('attackcompletecookie','attack_cookie');
});
$("#restore_enabled").click(function(){
createCookie('restorecompletecookie','restore_cookie');
var atkcomplete = readCookie('attackcompletecookie');
if(atkcomplete)
{
alert(atkcomplete);
$(".territory_middle_complete").addClass("displayblockzindex2");
}
});
function createCookie(cookieName, cookieId) {
document.cookie = cookieName + '=' + cookieId;
}
function readCookie(name) {
var nameEQ = encodeURIComponent(name) + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
} | unknown | |
d12316 | train | Run this command: sudo /etc/init.d/cron restart
after setting crontab demon has to restart.
Also check sys/log for tracing what is issue while running script. | unknown | |
d12317 | train | At first I thought that a CASE statement would be appropriate, but then I noticed that your logic always conditionally selects the same two columns a and b. So I think that what you need here is a WHERE clause to handle all the cases.
SELECT a, b
FROM tab
WHERE (x = 'x1' OR
((x = 'x2' OR x = 'x3') AND yy = 123) OR
(x = 'x4' AND yy = 456)) AND
zz = yy
A: You can use dynamic SQL and compose your query from different parts.
For example:
-- common part of query
common_query := 'SELECT a, b FROM tab WHERE zz= yy';
-- set additional condition
IF X=x1 THEN add_where := '';
ELSIF X=x2 OR X=x3 THEN add_where := ' AND yy= 123';
ELSIF X=x4 THEN add_where := ' AND yy= 456';
END IF;
-- compose final query
final_query:= common_query||add_where;
EXECUTE IMMEDIATE final_query;
Of couse when you use dynamic SQL you can use bind variables and you need to remember about return values. | unknown | |
d12318 | train | Put @Entity on your User class, if the table still not created try putting below annotations on the class:
@Entity
@Table(name = "`user`")
Could be happening because User is a reserve word in DB. | unknown | |
d12319 | train | Sure you can.
You need:
*
*Script that parses emails on schedule and adds those changes to some type of database
*Script that executes updates from the temporary database and adds that data to live database
How to read email with PHP:
$mb = imap_open("{host:port/imap}","username", "password" );
$messageCount = imap_num_msg($mb);
for( $MID = 1; $MID <= $messageCount; $MID++ )
{
$EmailHeaders = imap_headerinfo( $mb, $MID );
$Body = imap_fetchbody( $mb, $MID, 1 );
doSomething( $EmailHeaders, $Body );
}
read more
A: You would need some server side processing to be able to do this. This thread has a couple of ways of doing this using PHP, made easier with cPanel to make changes to the mail redirects. If you tell us more about your site and hosting environment, we may be able to give better suggestions.
The server side script would need to then parse your email and perform whatever updates your commands intend. Security is also very important, and it is trivial to forge the 'From' address when sending email. | unknown | |
d12320 | train | The EclipseLink Converter interface defines a initialize(DatabaseMapping mapping, Session session); method that you can use to set the type to use for the field. Someone else posted an example showing how to get the field from the mapping here: Using UUID with EclipseLink and PostgreSQL
The DatabaseField's columnDefinition, if set, will be the only thing used to define the type for DDL generation, so set it carefully. The other settings (not null, nullable etc) will only be used if the columnDefinition is left unset. | unknown | |
d12321 | train | working workaround
well i thought this woould work
<mx:Image x="0" y="0" source="{GameResource.bg}" mouseEnabled="false"/>
but for some reason it was occlding remaining controls and containers, despite it was added at the very first line (which makes ints displayindex = 0)
then I addeed this code to add them dynamically
var img:Image = new Image();
img.mouseEnabled = false;
img.mouseChildren = false;
img.source = GameResource.bg;
addChildAt(img,0);
working like charm. BLOODY FLEX VERY UNPREDICTABLE | unknown | |
d12322 | train | You should use regular expression and use function preg_replace() to replace matched string. Here is the full implementation of your special_text() function.
function special_text( $content ) {
$search_for = 'specialtext';
$replace_with = '<span class="special-text"><strong>special</strong>text</span>';
return preg_replace( '/<a.*?>(*SKIP)(*F)|'.$search_for.'/m', $replace_with, $content );
}
In the following regular expression first, using <a.*?> - everything between <a...> is matched and using (*SKIP)(*F)| it is skipped and then from anything else $search_for is matched (in your case it's specialtext).
A: Jezzabeanz quite got it except you can simplify it still with:
return preg_replace("/^def/", $replace_with, $content);
A: If you just want to change the text between the the a tags then a regular expression works wonders.
Here is something I used when I was pulling data from emails sent to me:
(?<=">)(.*?\w)(?=<\/a)
returns "specialtext"
It also returns "specialtext test" if there is whitespace.
Regular expressions are definitely the way to go.
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>
Source
And then do a replace on the returned matches. | unknown | |
d12323 | train | In fact. I have the same behavior. I don't know either it is a bug or a feature. A possible workaround is to use the Folder's toString() function. Something like
function typeOfTest() {
var folders = DocsList.getAllFolders();
for (var i = 0; i < folders.length; i++)
Logger.log(folders[i].toString());
}; | unknown | |
d12324 | train | Check out the docs for file uploads. Phoenix uses Plug.Upload. Your files will be uploaded to a temporary directory and only exists during the lifecycle of the upload request. You can choose to do whatever you want with that file. If you want to store it somewhere on your server, you might want to keep track of what files you upload and where they are stored on your server in your database. | unknown | |
d12325 | train | make it with pointer to function
Create a function for each operator.
int hh_div(int a, int b) {
// TBD: add some checks
return a / b;
}
int hh_add(int a, int b) {
// TBD: add some checks
return a + b;
}
Then use an array of function pointers indexed by char oper.
int do_it(char oper, int a, int b) {
static const int (*all[256])(int, int) = { //
['/'] = hh_div, //
['+'] = hh_add, //
// etc
};
int (*f)(int a, int b) = all[(unsigned char) oper];
if (f == NULL) {
Handle_NotDefined();
}
return f(a, b);
}
Code could use a big if() or switch(), but with a nice function look-up table, what is a 1 or 2 k-byte table between friends?
Of course the table could be smaller with some pre-tests.
Ref: Some 2 operand operators: % ^ & * + - | \ < > / | unknown | |
d12326 | train | You have 2 options to solve this.
First:
Edit your yaml file and replace the message with the below :
"%{attribute} has already been added to a location"
Second:
What you are getting is standard and correct output as per the current YAML configuration. But to get what you are looking for, without changing the YAML, need to use ActiveModel::Errors#full_messages.Because this method prepends the attribute name to the error message. | unknown | |
d12327 | train | Here's what the OpenCL 1.2 spec has to say about setting buffers as kernel arguments:
If the argument is a memory object (buffer, image or image array), the arg_value entry will be a pointer to the appropriate buffer, image or image array object.
So, you need to pass a pointer to the cl_mem objects:
ret=clSetKernelArg(kernel,0,sizeof(cl_mem),(void *) &Abuffer);
A: Why are you using clEnqueueTask? I think you should use clEnqueueNDRangeKernel if you have parallel work to do. Also, just set the global work size; pass NULL for the local work group size. 32x32 is larger than some devices can do. | unknown | |
d12328 | train | As you mentioned you are using font-awesome icons so i think you are missing the font-awesome reference link
add the below link inside your head it will work fine
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
also see the below code snippet i added Badges ,font-awesome icons and glyphicon for your help. you can Use whatever you like
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<style>
</style>
</head>
<body>
<div id="menuHTML">
<ul>
<li>
<a href="#">Catalogue</a>
<ul>
<li>
<a href="#">Bathroom <span class="glyphicon glyphicon-search" aria-hidden="true"> </span></a>
</li>
<li>
<a href="#">Bedroom <span class="badge">42</span></a>
</li>
<li>
<a href="#">Kitchen <i class="sm-set-icon fa fa-play"></i> Play</a>
</li>
<li>
<a href="#">Living Room</a>
</li>
</ul>
</li>
<li>
<a href="#">Orders</a>
<ul>
<li>
<a href="#">Pending</a>
</li>
<li>
<a href="#">Completed</a>
</li>
<li>
<a href="#">Other</a>
</li>
</ul>
</li>
</ul>
</div>
</body>
</html> | unknown | |
d12329 | train | An engine is going to help you because it already has some basic functionalities, like: collision handling, sprites and so on! In other words you don't need to be concerned about coding in order to solve basic problems that every single game has in common!(you will write fewer lines of code) Look I'm not an expert in this subject but you can try: Cocos 2D and AndEngine, take a look at the links bellow:
http://cocos2d.org/
http://www.andengine.org/
I hope it will be usefull!
see you! | unknown | |
d12330 | train | I just figured it out.
*
*I renamed the targets to pre-build and post-build without -.
*I went to External Tools Configurations and selected build.xml to the left. On the right, I went to the tab Targets, checked my two targets (in addition to the build target which already had a checkmark) and set the order to be pre-build, build, post-build.
*I went to the project properties and I selected Builders on the left. I created a new builder using the build.xml file and having the three targets from the previous bullet point, in the same order. I placed this builder before the Java builder.
*I removed the post-build target as it puts the version back to 0 and seems to do that earlier than I would like.
I am still not sure that this is the optimal solution. Also, the solution fails when there is no git versioning. I tried using this code for solving the issue but it didn't worked. Nevertheless, it is the best I could do and it helps me getting the info I need in the app.
A: Use Git executable with Argument --version and catch the output in a property for further usage, f.e. :
<project>
<exec executable="git" outputproperty="gitversion">
<arg value="--version"/>
</exec>
<echo>$${gitversion} => ${gitversion}</echo>
</project>
output :
[echo] ${gitversion} => git version 1.8.3.msysgit.0 | unknown | |
d12331 | train | You need to specify an instance of the Food class, so this argument is incorrect:
target:[Food class]
So what you are passing to NSTimer is a Class object, not a Food object.
Instead you probably need an instance variable of the Food instance and specify that:
@interface MyClass ()
{
Food *_food;
}
@implementation MyClass
...
- (void)whatever
{
_food = [Food new]; // This might need to be elsewhere
SEL selector = @selector(addCloudOne);
[NSTimer scheduledTimerWithTimeInterval:k1
target:_food
selector:selector
userInfo:nil
repeats:YES];
} | unknown | |
d12332 | train | First, you can create default DataGenerator to plot original images easily
datagenOrj = keras.preprocessing.image.ImageDataGenerator()
You can flow a small sample like the first five images into your 'datagen'. This generator gets images randomly. To making a proper comparison, small and certain sampling can be good for large dataset.
result_data = datagen.flow(train_data[0:5], train_label[0:5], batch_size=128)
result_data_orj = datagenOrj.flow(train_data[0:5], train_label[0:5], batch_size=128)
When you call the next() function, your data generator loads your first batch. The result should contain both train data and train label. You can access them by index.
def getSamplesFromDataGen(resultData):
x = resultData.next() #fetch the first batch
a = x[0] # train data
b = x[1] # train label
for i in range(0,5):
plt.imshow(a[i])
plt.title(b[i])
plt.show()
Be carefull about plotting. You may need to rescale your data. If your data type is float, you need to scale it between 0 and 1 and if your data type integer, you should scale it between 0 and 255. To do it you can use rescale property.
datagenOrj = keras.preprocessing.image.ImageDataGenerator(rescale=1.0/255.0)
I tried on my own dataset and it is working.
Best | unknown | |
d12333 | train | ffmpeg currently doesn't support muxing AV1 in WebM. The error you're getting comes from this code:
if (mkv->mode == MODE_WEBM && !(par->codec_id == AV_CODEC_ID_VP8 ||
par->codec_id == AV_CODEC_ID_VP9 ||
par->codec_id == AV_CODEC_ID_OPUS ||
par->codec_id == AV_CODEC_ID_VORBIS ||
par->codec_id == AV_CODEC_ID_WEBVTT)) {
av_log(s, AV_LOG_ERROR,
"Only VP8 or VP9 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
return AVERROR(EINVAL);
}
Note the lack of AV_CODEC_ID_AV1 in the expression.
This isn't too surprising, though. AV1 in Matroska (and therefore WebM) hasn't been finalized yet. If you want to follow progress on AV1 in Matroska (and WebM), follow the discussion here on the IETF CELLAR mailing list.
A: Update, FFmpeg does support AV1 in Webm now!
if (!native_id) {
av_log(s, AV_LOG_ERROR,
"Only VP8 or VP9 or AV1 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
return AVERROR(EINVAL);
}
Source code here. | unknown | |
d12334 | train | The Recipients of a Message (and a number of other properites) aren't returned when you use a FindItem request you need to make a GetItem request http://msdn.microsoft.com/en-us/library/office/aa565934(v=exchg.150).aspx on the particular ItemId you want to get the recipients for. If you need to do this for a large number of Items you can batch the GetItems Request eg http://blogs.msdn.com/b/exchangedev/archive/2010/03/16/loading-properties-for-multiple-items-with-one-call-to-exchange-web-services.aspx
Cheers
Glen | unknown | |
d12335 | train | Clicking on the language button in the lower right corner and selecting typescript react fixed the problem.
A: I faced same problem, even "Typescript React" was selected as the language. I had to click and select the language pack version before getting syntax highlighting working.
A: In my case "JavaScript and TypeScript Nightly" extension was causing the problem.
I had the same problem even when "Typescript React" was selected.
I disabled all the extensions and problem solved.
Then I enabled each extension individually and I've found out "JavaScript and TypeScript Nightly" was causing the problem.
I hope this will help someone.
A: I solved this issue just reloading vscode as required by JavaScript and TypeScript Nightly extension, once it was reload I just double checked that Typescript react was selected and the problem was resolved.
Seems like the real problem was that the library JavaScript and TypeScript Nightly was not fully reloaded. | unknown | |
d12336 | train | Managed to solve the problem with the following initializer;
Rails.application.config.middleware.use OmniAuth::Builder do
provider :coinbase, ENV['CLIENT_ID'], ENV['CLIENT_SECRET'],
scope: 'wallet:user:read wallet:user:email wallet:accounts:read wallet:transactions:send',
:meta => {'send_limit_amount' => 1}
end
Now, I need to either disable the two factor authentication or determine how to Re-play the request with CB-2FA-Token header | unknown | |
d12337 | train | #import is not enough. Read What is the difference between include and link when linking to a library? and search for similar questions.
You have to link binary with this library:
Select your target, switch to Build Phases and add libbsm to Link Binary with Libraries section.
Or add -l bsm to clang command line options. | unknown | |
d12338 | train | Not using an enum, but you can get the same exact thing using a class and a few static members:
class Planet {
public static MERCURY = new Planet(3.303e+23, 2.4397e6);
public static VENUS = new Planet(4.869e+24, 6.0518e6);
public static EARTH = new Planet(5.976e+24, 6.37814e6);
public static MARS = new Planet(6.421e+23, 3.3972e6);
public static JUPITER = new Planet(1.9e+27, 7.1492e7);
public static SATURN = new Planet(5.688e+26, 6.0268e7);
public static URANUS = new Planet(8.686e+25, 2.5559e7);
public static NEPTUNE = new Planet(1.024e+26, 2.4746e7);
private mass: number;
private radius: number;
private constructor(mass: number, radius: number) {
this.mass = mass;
this.radius = radius;
}
public static G = 6.67300E-11;
public surfaceGravity(): number {
return Planet.G * this.mass / (this.radius * this.radius);
}
public surfaceWeight(otherMass: number) {
return otherMass * this.surfaceGravity();
}
}
console.log(Planet.MERCURY.surfaceGravity());
(code in playground)
In java for each item in the enum a static instance is created, which means that this indeed does the same thing, it's just that java has a nicer syntax for defining enums.
Edit
Here's a version with the equivalent Planet.values() which java will generate:
class Planet {
public static MERCURY = new Planet(3.303e+23, 2.4397e6);
public static VENUS = new Planet(4.869e+24, 6.0518e6);
...
private static VALUES: Planet[] = [];
private mass: number;
private radius: number;
private constructor(mass: number, radius: number) {
this.mass = mass;
this.radius = radius;
Planet.VALUES.push(this);
}
public static values() {
return Planet.VALUES;
}
...
}
2nd edit
Here's a way to implement the valueOf:
public static valueOf(name: string): Planet | null {
const names = Object.keys(this);
for (let i = 0; i < names.length; i++) {
if (this[names[i]] instanceof Planet && name.toLowerCase() === names[i].toLowerCase()) {
return this[names[i]];
}
}
return null;
}
A: Unfortunately it's not possible. You can just assign property names
See this reference for the TypeScript spec https://github.com/microsoft/TypeScript/blob/30cb20434a6b117e007a4959b2a7c16489f86069/doc/spec-ARCHIVED.md#a7-enums
A: You can get the 'same thing' using a const.
Obviously this solution isn't exactly like enumerations, it's just a different use of the keys of a const object instead of an actual enumeration value.
export const OrderStateEnum = {
WAITING_SCORING: { key: 1, value: "WAITING for SCORING" },
WAITING_ACCEPTANCE: { key: 2, value: "Waiting for acceptance" },
ORDER_ACCEPTED: { key: 3, value: "Order accepted" },
} as const
export type OrderStateEnum = keyof typeof OrderStateEnum
export function valueOf(value: string): OrderStateEnum{
for(var key in OrderStateEnum) {
if(value.toLowerCase()=== OrderStateEnum[key].value.toLowerCase()){
return OrderStateEnum[key];
}
}
}
To receive all the values of the false enum:
states = OrderStateEnum;
To receive a certain value of the false enum:
OrderStateEnum.WAITING_SCORING.value;
Below is a usage via *ngFor
<select formControlName="statoOrdine" [(ngModel)]="stato">
<option *ngFor="let item of states | keyvalue" [value]="item.value.key">
{{item.value.value}}</option>
</select> | unknown | |
d12339 | train | The idea of command line arguments is to change the behaviour of your executable file at run time, so you don't need to re-compile your source code if you want slightly different behaviour.
Just call your program like ./cddb -l and parse the command line arguments in your source code. To parse the arguments you can use the argv and argc variables declared in the main function signature. | unknown | |
d12340 | train | I don't know kendo but I found this:
http://docs.telerik.com/kendo-ui/AngularJS/introduction#widget-update-upon-option-changes
You can also read about controller-directive communication and about scope.$watch, scope.$on | unknown | |
d12341 | train | An easy way is to convert the dates to YYYYMMDD format that can be sorted lexicographically.
Note that MM should be the month represented as a two digit number.
A: You could use the core module Time::Piece to convert the DD-MMM-YY (or any input format) to an ISO 8601 form. This allows simple sorting. This example builds up an array of raw data which includes the ISO value as a sort key; sorts it; and returns the data in sorted order:
#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece;
my $t;
my @data;
while (<DATA>) {
chomp;
$t = Time::Piece->strptime( $_, "%d %b %y" );
push @data, [ $t->datetime, $_ ]; #...ISO 8601 format...
}
my @sorteddata = sort { $a->[0] cmp $b->[0] } @data;
for my $value (@sorteddata) {
print $value->[1], "\n";
}
__DATA__
19 Feb 12
17 Aug 11
31 Mar 10
01 Aug 11
08 Apr 11
29 Feb 11
A: This can be done using the Time::Piece core module's strptime method to decode the dates and sorting them according to the resulting epoch seconds.
This program demonstrates the idea.
use strict;
use warnings;
use Time::Piece;
my @dates = <DATA>;
chomp @dates;
my @sorted = sort {
Time::Piece->strptime($a, '%d-%b-%y') <=> Time::Piece->strptime($b, '%d-%b-%y')
} @dates;
print "$_\n" for @sorted;
__DATA__
05-FEB-12
10-MAR-11
22-AUG-11
26-FEB-12
10-NOV-12
07-JUN-11
20-APR-12
19-DEC-12
17-JAN-11
25-NOV-11
28-FEB-11
04-SEP-11
03-DEC-12
16-SEP-12
31-DEC-11
08-JUN-11
22-JUN-12
02-AUG-12
23-SEP-11
14-MAY-11
output
17-JAN-11
28-FEB-11
10-MAR-11
14-MAY-11
07-JUN-11
08-JUN-11
22-AUG-11
04-SEP-11
23-SEP-11
25-NOV-11
31-DEC-11
05-FEB-12
26-FEB-12
20-APR-12
22-JUN-12
02-AUG-12
16-SEP-12
10-NOV-12
03-DEC-12
19-DEC-12
A: Here's a possible way to do this using only basic Perl (no modules):
#! perl -w
use strict;
my @dates = ( '19-FEB-12', '15-APR-12', '13-JAN-11' );
# map month names to numbers
my %monthnum = (
'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4,
'MAY' => 5, 'JUN' => 6, 'JUL' => 7, 'AUG' => 8,
'SEP' => 9, 'OCT' => 10, 'NOV' => 11, 'DEC' => 12
);
# sort the array using a helper function
my @sorted_dates = sort { convert_date($a) cmp convert_date($b) } @dates;
print join(", ", @sorted_dates), "\n";
# outputs: 13-JAN-11, 19-FEB-12, 15-APR-12
exit(0);
# THE END
# converts from 19-FEB-12 to 120219, for sorting
sub convert_date
{
my $d1 = shift;
my $d2;
if ($d1 =~ /(\d{2})-([A-Z]{3})-(\d{2})/)
{
$d2 = sprintf( "%02d%02d%2d", $3, $monthnum{$2}, $1 );
}
else
{
die "Unrecognized format: $d1";
}
return $d2;
}
This relies on your dates being formatted correctly, but it should be trivial to add more validation.
A: Using DateTime module;
or use sort command with month option (*nix);
or transform dd-mmm-yyyy to yyyymmdd and then sort;
A: Totally from scratch:
Printed Output:
Unsorted:
14-OCT-06
15-OCT-06
13-OCT-06
19-FEB-12
29-DEC-02
15-JAN-02
Sorted (Least recent to most recent):
15-JAN-02
29-DEC-02
13-OCT-06
14-OCT-06
15-OCT-06
19-FEB-12
Code:
#!C:\Perl64
#Input Strings
@inputs = ('14-OCT-06','15-OCT-06','13-OCT-06', '19-FEB-12', '29-DEC-02', '15-JAN-02');
print "Unsorted:\n";
foreach(@inputs){
print $_."\n";
}
# Hash for Month : Number
%months = ('JAN' => '01',
'FEB' => '02',
'MAR' => '03',
'APR' => '04',
'MAY' => '05',
'JUN' => '06',
'JUL' => '07',
'AUG' => '08',
'SEP' => '09',
'OCT' => '10',
'NOV' => '11',
'DEC' => '12');
# Hash for Number : Month
%revmonths = ('01'=>'JAN',
'02' => 'FEB',
'03' => 'MAR',
'04' => 'APR',
'05' => 'MAY',
'06' => 'JUN',
'07' => 'JUL',
'08' => 'AUG',
'09' => 'SEP',
'10' => 'OCT',
'11' => 'NOV',
'12' => 'DEC');
# Rearrange the order to 'Year-Month-Day'
@dates = ();
foreach(@inputs){
my @split = split('-',$_);
my @rearranged = reverse(@split);
@rearranged[1] = $months{$rearranged[1]};
push(@dates, \@rearranged);
}
# Sort based on these three fields
@sorted = sort { $a->[2] <=> $b->[2] } @dates;
@sorted = sort { $a->[1] <=> $b->[1] } @sorted;
@sorted = sort { $a->[0] <=> $b->[0] } @sorted;
# Replace Month Number with Month name
$size = @sorted;
for $counter (0..$size-1){
my $ref = $sorted[$counter];
my @array = @$ref;
my $num = $array[1];
$array[1] = $revmonths{$array[1]};
my @array = reverse(@array);
$sorted[$counter] = \@array;
}
print "\nSorted (Least recent to most recent):\n";
foreach(@sorted){
my @temp = @$_;
my $day = $temp[0];
my $month = $temp[1];
my $year = $temp[2];
print $day."-".$month."-".$year;
print "\n";
} | unknown | |
d12342 | train | This happens because @position.questions is not an array. It's actually an ActiveRecord::Relation. The problem is that the console actually behaves differently from your server application.
For example, in your console position.questions returns an array. That is because the console is actually evaluating this expression as position.questions.all which is equivalent to position.questions.to_a. In your server application the to_a or all is not called until you actually use the query. This is a good thing because it means you can continue to build up a query and it will only actually get executed when it's called.
For instance:
query = @position.questions
query.first
query.last
Will actually generate two queries that return two records in your server application because the query variable will be assigned an ActiveRecord::Relation instead of an Array. In your console this will generate a single query, but the query will load all of the questions into an Array and assign that to query and then select the first and last elements.
The all, first, last, count and even include? keywords are all triggers that actually execute the query, so in your application when you call @position.questions.include? you are executing a single query on the @position.questions relation. Adding the to_a causes this query to be executed immediately. | unknown | |
d12343 | train | It is much easier to break out the actual value check to a helper function that works on a single element. That way you can easily see where you unpack the Maybe value
isSudokuValues :: (Ix a, Num a) => [Maybe a] -> [Bool]
isSudokuValues =
let
isSudokuValue :: (Ix a, Num a) => Maybe a -> Bool
isSudokuValue Nothing = True
isSudokuValue (Just x) = inRange (1, 9) x
in map isSudokuValue
A: I think you make two errors:
maybe has the following signature:
b -> (a -> b) -> Maybe a -> b
So you should use:
map (maybe True $ inRange (1,9)) list
the fromJust cannot be used, since then maybe would work on a (instead of Maybe a, and furthermore it is one of the tasks of maybe simply to allow safe data processing (such that you don't have to worry about whether the value is Nothing.
Some Haskell users furthermore consider fromJust to be harmfull: there is no guarantee that a value is a Just, so even if you manage to let it work with fromJust, it will error on Nothing, since fromJust cannot handle these. Total programming is one of the things most Haskell programmers aim at.
Demo (with ghci):
Prelude Data.Maybe Data.Ix> (map (maybe True $ inRange (1,9))) [Just 1, Just 15, Just 0, Nothing]
[True,False,False,True]
Prelude Data.Maybe Data.Ix> :t (map (maybe True $ inRange (1,9)))
(map (maybe True $ inRange (1,9))) :: (Num a, Ix a) => [Maybe a] -> [Bool] | unknown | |
d12344 | train | from navigationOption you can not do anything to other screen,
so what you can do is, move your header code into another file and use it as component in TabNav
something like this,
let say Header.js
<View style={{ backgroundColor: '#025281', flexDirection:
'row', alignItems: 'center', height: 60 }}>
<TouchableOpacity
style={{ paddingLeft: 5 }}>
<Image source={require(back_arrowimg)} style={{
width: 25, height: 25, resizeMode: 'contain' }}/>
</TouchableOpacity>
<TextInput
style={{ color: 'white', paddingLeft: 15, }}
type='text'
placeholder={headerTitle}
onChangeText={this.props.loadUsers} // see this change
/>
</View>
and in your TabNav.js use header as component,
<Header
loadUsers={(...your params)=>{
//do your necessary stuffs to display data in this file
}) /> | unknown | |
d12345 | train | I will try to explain with an example with use x2js.js https://github.com/abdmob/x2js and jquery (and without jQuery) library.
GET XML data from the API and convert this data to JSON
With jQuery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
<script type="text/javascript" src="xml2json.js"></script>
</head>
<body>
<script type="text/javascript">
var x2js = new X2JS();
$.ajax({
url: 'http://ip-api.com/xml',
dataType: 'XML',
success: function(data) {
var xmlText = data; // XML
var jsonObj = x2js.xml2json(xmlText); // Convert XML to JSON
console.log(jsonObj);
}
});
</script>
</body>
</html>
without jQuery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="xml2json.js"></script>
</head>
<body>
<script type="text/javascript">
function loadXMLDoc(dname) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", dname, false);
xhttp.send();
return xhttp.responseXML;
}
var xmlDoc = loadXMLDoc("http://ip-api.com/xml"); // XML
var x2js = new X2JS();
var jsonObj = x2js.xml2json(xmlDoc); // Convert XML to JSON
console.log(jsonObj);
</script>
</body>
</html>
and using the example that you gave in question. Fix closed <result> to </result>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="xml2json.js"></script>
</head>
<body>
<script type="text/javascript">
var txt = "<?xml version='1.0' encoding='UTF-8' ?> <result> <info> <id>1</id> <type>HL</type> <ven>DEMOMA</ven> </info> <info> <id>2</id> <type>HL</type> <ven>DEMOMB</ven> </info> </result>";
var x2js = new X2JS();
var jsonObj = x2js.xml_str2json(txt);
console.log(jsonObj);
</script>
</body>
</html>
A: Check out this https://github.com/metatribal/xmlToJSON
Its a very small and useful script. Usage is very easy.
Include the src
<script type="text/javascript" src="path/xmlToJSON.js"></script>
and enjoy! xmlToJSON is packaged as a simple module, so use it like this
testString = '<xml><a>It Works!</a></xml>'; // get some xml (string or document/node)
result = xmlToJSON.parseString(testString); // parse
'result' is your JSON object. | unknown | |
d12346 | train | As @zx8754 menitioned, you should provide reproducible data.
Without having tested the code (because there's no reproducible data), I would suggest the following, assuming that the data is in the data.frame 'data':
all_products <- unique(data$Product)
colors_use <- rainbow(length(all_products))
plot(y = data[data$Product == all_products[1],"Balance"],
x = data[data$Product == all_products[1],"Origination"],
type = "l",
col = colors_use[1],
ylim = c(min(data$Balance, na.rm = T),max(data$Balance, na.rm = T)),
xlim = c(min(data$Origination, na.rm = T),max(data$Origination, na.rm = T)))
for(i_product in 2:length(all_products)){
lines(y = data[data$Product == all_products[i_product],"Balance"],
x = data[data$Product == all_products[i_product],"Origination"],
col = colors_use[i_product])
}
A: I have not enough reputation to comment, so I write it as an answer. To make @tobiasegli_te's answer shorter, the first plot can be plot(Balance~Origination,data=data,type='n') and then make the subsequent lines done for i_product in 1:length(all_products). That way you need not worry about ylim. Here is an example using the Grunfeld data.
z <- read.csv('http://statmath.wu-wien.ac.at/~zeileis/grunfeld/Grunfeld.csv')
plot(invest~year,data=z,type='n')
for (i in unique(as.numeric(z$firm))) lines(invest~year,data=z,
subset=as.numeric(z$firm)==i, col=i)
Also note that your Origination is not equally spaced. You need to change it to a Date or similar.
A: I guess you want something like the following:
df <- as.data.frame(df[c('Product', 'Balance', 'Origination')])
head(df)
Product Balance Origination
1 DEMAND DEPOSITS 2586.25 198209
2 DEMAND DEPOSITS 3557.73 198304
3 DEMAND DEPOSITS 14923.72 198308
4 DEMAND DEPOSITS 4431.67 198401
5 DEMAND DEPOSITS 44555.23 198410
6 MONEY MARKET ACCOUNTS 65710.01 198209
library(ggplot2)
library(scales)
ggplot(df, aes(Origination, Balance, group=Product, col=Product)) +
geom_line(lwd=1.2) + scale_y_continuous(labels = comma)
A: I am not sure what you my want, is that what you re looking for?
Assuming you put your data in data.txt, removing the pipes and replacing the spaces in the names by '_'
d = read.table("data.txt", header=T)
prod.col = c("red", "blue", "green", "black" )
prod = unique(d$Product)
par(mai = c(0.8, 1.8, 0.8, 0.8))
plot(1, yaxt = 'n', type = "n", axes = TRUE, xlab = "Origination", ylab = "", xlim = c(min(d$Origination), max(d$Origination)), ylim=c(0, nrow(d)+5) )
axis(2, at=seq(1:nrow(d)), labels=d$Product, las = 2, cex.axis=0.5)
mtext(side=2, line=7, "Products")
for( i in 1:nrow(d) ){
myProd = d$Product[i]
myCol = prod.col[which(prod == myProd)]
myOrig = d$Origination[i]
segments( x0 = 0, x1 = myOrig, y0 = i, y1 = i, col = myCol, lwd = 5 )
}
legend( "topright", col=prod.col, legend=prod, cex=0.3, lty=c(1,1), bg="white" ) | unknown | |
d12347 | train | You could use @media screen instead of just @media so that the codes will work in screen but not in the print version.
Example:
@media screen and (min-width: 991px) {
div.container{
font-size:18px;
}
} | unknown | |
d12348 | train | Found the solution in this error
some steps to solve this problem
*
*go to Apps page Dropbox apps
*add your site or localhost link to OAuth 2 Redirect URIs
*next to generate access token, then copy the access token and use it .
*finally remove this lines
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
and paste directly in your access token into
$accessToken =
"VTEp2cvkQ8************************************";
it's working perfectly | unknown | |
d12349 | train | Answering my own question...
Did you check if you have any thing to open a PDF on your device which has iOS5 on it? Don't forget iBooks is not installed by default and iOS does not think to use Safari as a PDF reader. | unknown | |
d12350 | train | The code you have written seems unrelated to the actual error code. The error code specifically describes this problem:
.../albumart.lua:68: attempt to concatenate global 'album' (a nil value)
This means that you are trying to concatenate the album variable using the concatenate operator .., and it's value happens to be nil.
The code you have written suggests that this should not be the case (even though you may want to try make all the variables in the function local). Please take a look at line 68 in your file to find the problem. | unknown | |
d12351 | train | Using the regex modifier x enables comments in the regex. So the # in your regex is interpreted as a comment character and the rest of the regex is ignored. You'll need to either escape the # or remove the x modifier.
Btw: There's no need to escape the parentheses inside []. | unknown | |
d12352 | train | First of all, make sure your aspects (annotation-based or native syntax) always have a .aj file extension (add them to your project via "New aspect" instead of "New class" menu in whatever IDE you use). I have removed the duplicate class from your repo in my fork and renamed the other one accordingly. I chose the native syntax one, by the way.
What was worse, though, is that you somehow expect unwoven Scala classes in a specific directory, but you did not configure the Scala plugin to actually put them there. I fixed that by adding this snippet:
<configuration>
<outputDir>${project.build.directory}/unwoven-classes</outputDir>
</configuration>
Now the AspectJ Maven plugin finds the Scala classes there and performs binary weaving upon them. This fixes both your Java and Scala test. Both of them failed in Maven before, now at least the Java one works in IntelliJ, but not the Scala one. This is due to the fact that IDEA does not know about this strange Maven setup with the additional (intermediate) directory of yours.
So there is nothing wrong with the aspect as such or AspectJ being unable to work with Scala binaries. The project setup was wrong and in a way it still is with respect to IDE support.
So how can you fix it completely? You have several options:
*
*Put the aspect code into another Maven module and there configure a weave dependency on the Java + Scala module, weaving all classes from there into the aspect module. But then you might still have issues with running the tests. But at least you could configure the IDEA project for post-compile weaving with the right dependency.
*You could also put the Scala code in its own module instead, define it as a dependency for the Java + AspectJ module and apply binary weaving to it that way.
Other variants are possible. I do not want to over-analyse here, I just fixed your Maven setup in a quick and simple approach to get you going:
$ mvn clean verify
(...)
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Aktive Codepage: 65001.
Running aspects.AnnotationAspectTest
set(String model.JavaEntity.name)
set(String model.ScalaEntity.name)
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.055 sec
Results :
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ aspectj-with-scala ---
[INFO] Building jar: C:\Users\Alexander\Documents\java-src\aspectj-with-scala\target\aspectj-with-scala-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
(...)
P.S.: I have also created a pull request for you to easily integrate my changes into your repo.
P.P.S.: See, an MCVE is more helpful than what you did before: Post a separate question only showing an aspect and then post this question here with only a Maven POM. I needed both plus the other classes in order to reproduce and solve the problem. After you published the GitHub project it was pretty straightforward to find and fix.
A: The problem is likely that aspects are often applied to the semantics of your java code - "find a method with a name like X and do the following around it." But Scala code, when viewed from Java, typically does not follow expected naming conventions. Without more detail on the specific pointcuts being made - and the code on which they're being applied - I couldn't give any more insight. | unknown | |
d12353 | train | Does the view show documents in a response hierarchy? Probably there is an "orphaned" response (Replication conflict or other reason) that is not shown in the view as the parent document is missing, but still is counted in the total- column. Try disable response- hierarchy in the View- Properties and check if there is such a document.
An additional reason for the total not being 0 could also be a document that is protected by a readers- field. Server will add this document to the totals (as View- Index is created by the server) whereas the Designer / User does not see the document.
If you know, what is in the Readers- Field (Role, GroupName, etc.) then make yourself member of that field (by assigning the Role to yourself or add yourself to the group).
If you don't know, what's in there (or something went wrong filling the readers field, e.g. forgot to tick the "multi value"- property), then you need somebody with "Full Access Administration"- right to the server. This Admin- function ovverrides all Reader- fields and makes the document visible to you. | unknown | |
d12354 | train | Parent of the box:
{
overflow-y: auto
}
A: .pull-quote {
background: #fb8063;
width: 300%;
margin: 30px 0 30px -100%;
z-index: 70;
position: relative;
overflow: hidden;
}
this merely clips overflow, and the rest of the content will be invisible
some other things to consider is to resize the whole orange box as well as the tags with it.
other overflow css you can try are: scroll, auto, etc.
quite possibly even set the width of the orange box to be fixed and display it within a div tag that has a background of orange.
hope this helps | unknown | |
d12355 | train | IP of "ip-172-31-90-9" seems private IP address.
So what you need do:
*
*assign public IP or Elastic IP to that ec2 instance.
*set inbound rule in its security group and open the port 5432 to 0.0.0.0/0 or any IP ranges in your case
*test the port from your local
telnet NEW_Public_IP 5432
If can, then you should be fine to connect the database. | unknown | |
d12356 | train | Still, the Python3 is experimental in Kivy.
https://kivy.org/doc/stable/guide/packaging-android.html
If you can work in Python2 better try that. | unknown | |
d12357 | train | I don't know if this is the answer you want, but if you want to have a fallback page for each base route, the easiest way is to use nested switch.
import React, { Component } from "react";
import { render } from "react-dom";
import { Route, Switch, BrowserRouter } from "react-router-dom";
const Home = props => (
<div>
<Switch>
<Route path={props.match.url + "/1"} exact render={() => <h1>Home 1</h1>} />
<Route path={props.match.url + "/2"} exact render={() => <h1>Home 2</h1>} />
<Route render={() => <h1>Home 404</h1>} />
</Switch>
</div>
);
const Post = props => (
<div>
<Switch>
<Route path={props.match.url + "/1"} exact render={() => <h1>Post 1</h1>} />
<Route path={props.match.url + "/2"} exact render={() => <h1>Post 2</h1>} />
<Route render={() => <h1>Post 404</h1>} />
</Switch>
</div>
);
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<Switch>
<Route path="/home" component={Home} />
<Route path="/post" component={Post} />
<Route render={() => <h1>404</h1>} />
</Switch>
</div>
</BrowserRouter>
);
}
}
*
*The authentication can be done in each root route component, and then redirect to login page.
*Query parameter also can be used, so the same route can handle multiple ids.
Eg: <Route path={this.props.match.url + '/:id'} exact component={Post} /> and then, in Post component, using const { id } = this.props.match.params to get the id.
There is the CodeSandbox demo. | unknown | |
d12358 | train | Reset the value of stepper while loading your cell. you can reset the cell property values in cell's prepareForReuse method. add the following method in your ReviewTableViewCell class.
override func prepareForReuse()
{
super.prepareForReuse()
countStepper.value = 0.0
}
A: In tableViewCell VC:
1 - add these field
var cellDelegate: cellProtocol?
var index: IndexPath?
2 - then add this in the delegate:
func onStepperClick(index: Int, sender: UIStepper)
3 - when you have dragged your stepper over as an action use this:
@IBAction func cellStepper(_ sender: UIStepper) {
cellDelegate?.onStepperClick(index: (index?.row)!, sender: sender)
sender.maximumValue = 1 //for incrementing
sender.minimumValue = -1 //for decrementing
//this will make sense later
}
In ViewController
1 - add these to the tableView function that has the cellAtRow variable.
cell.cellDelegate = self
cell.index = indexPath
2 - Use this instead of your stepperButton function
func onStepperClick(index: Int, sender: UIStepper) {
print(index)
if sender.value == 1.0{
//positive side of stepper was pressed
}else if sender.value == -1.0{
//negative side of stepper was pressed
}
sender.value = 0 //resetting to zero so sender.value produce different values on plus and minus
}
Hope this works for you
A: As mentioned by @A-Live, your component is being reused and so need to be updated.
So in your view controller:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "reviewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ReviewTableViewCell
var imageView: UIImageView?
let photoG = self.photos[indexPath.row]
imageView = cell.contentView.viewWithTag(1) as? UIImageView
//let layout = cell.goodiesImage
let tag = indexPath.row // +1
cell.tag = tag
photoG.fetchImageWithSize(CGSize(width: 1000, height: 1000), completeBlock: { image, info in
if cell.tag == tag {
imageView?.image = image
cell.goodiesImage.image = image
}
})
cell.countStepper.value = XXX[indexPath.row].value; //Here you update your view
cell.stepperLabel.text = "x \(Int(cell.countStepper.value))" //And here
And
func stepperButton(sender: ReviewTableViewCell) {
if let indexPath = tableView.indexPathForCell(sender){
print(indexPath)
XXX[sender.tag].value = sender.counterStepper.value //Here you save your updated value
}
A: NOTE:
1.MY Cell class is just normal..All changes are in viewcontroller class
2.I have taken stepper and over it added ibAddButton with same constraint as ibStepper
class cell: UITableViewCell {
@IBOutlet weak var ibAddButton: UIButton!
@IBOutlet weak var ibStepper: UIStepper!
@IBOutlet weak var ibCount: UILabel!
@IBOutlet weak var ibLbl: UILabel!
}
1.define empty int array [Int]()
var countArray = [Int]()
2.append countArray with all zeros with the number of data u want to populate in tableview
for arr in self.responseArray{
self.countArray.append(0)
}
3.in cell for row at
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! cell
let dict = responseArray[indexPath.row] as? NSDictionary ?? NSDictionary()
cell.ibLbl.text = dict["name"] as? String ?? String()
if countArray[indexPath.row] == 0{
cell.ibAddButton.tag = indexPath.row
cell.ibStepper.isHidden = true
cell.ibAddButton.isHidden = false
cell.ibCount.isHidden = true
cell.ibAddButton.addTarget(self, action: #selector(addPressed(sender:)), for: .touchUpInside)
}else{
cell.ibAddButton.isHidden = true
cell.ibStepper.isHidden = false
cell.ibStepper.tag = indexPath.row
cell.ibCount.isHidden = false
cell.ibCount.text = "\(countArray[indexPath.row])"
cell.ibStepper.addTarget(self, action: #selector(stepperValueChanged(sender:)), for: .valueChanged)}
return cell
}
4.objc functions
@objc func stepperValueChanged(sender : UIStepper){
if sender.stepValue != 0{
countArray[sender.tag] = Int(sender.value)
}
ibTableView.reloadData()
}
@objc func addPressed(sender : UIButton){
countArray[sender.tag] = 1//countArray[sender.tag] + 1
ibTableView.reloadData()
} | unknown | |
d12359 | train | The date format can be defined from SSDT. Highlight the date column and go to the properties window (press F4). For the Data Format property select the desired date format. If you need a date format that's not listed a calculated column using the FORMAT function can be created based off the original column, with the data type of this column then set to Date. An example of this is below. Additionally, confirm the Locale Identifier (LCID) in SSDT. This can by viewed by selecting Model > Existing Connections > Edit > Build > All > then the Locale Identifier property. The Microsoft documentation provides details in regards to identifying the correct LCID.
=FORMAT('Process'[Process Date], "dd-MM-yyyy") | unknown | |
d12360 | train | The charts options are case sensitive. You specified 'yaxis' when it should be 'yAxis'. That took me a while to spot !
series: [{
yAxis: 1,
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
},{
yAxis: 0,
data: [19.9, 21.5, 6.4, 29.2, 44.0, 76.0, 35.6, 48.5, 16.4, 94.1, 95.6, 54.4]
}] | unknown | |
d12361 | train | Your second variant does not work, because you are using the wrong interface (Function expects an input argument) and no syntax to create a function instance, but just an ordinary invocation expression.
You have several choices
*
*Use Supplier. This interface describes a function without parameters and returning a value.
public static <T> T withPaging(Supplier<T> call, int pageSize, int pageNumber) {
try {
PaginationKit.setPaginationInput(pageSize, pageNumber); // Set threadlocal
return call.get();
} finally {
PaginationKit.clearPaginationInput(); // Clear threadlocal
}
}
Instead of insisting on it to return List<T>, we simply allow any return type which raises its versatility. It includes the possibility to return a List of something.
Then, we may use either, a method reference
List<SpecialObject> results=PaginationDecorator.withPaging(
specialService::getSpecialObjs, pageSize, pageNumber);
or a lambda expression:
List<SpecialObject> results=PaginationDecorator.withPaging(
() -> specialService.getSpecialObjs(), pageSize, pageNumber);
*Stay with Function, but allow the caller to pass the required argument
public static <T,R> R withPaging(
Function<T,R> call, T argument, int pageSize, int pageNumber) {
try {
PaginationKit.setPaginationInput(pageSize, pageNumber); // Set threadlocal
return call.apply(argument);
} finally {
PaginationKit.clearPaginationInput(); // Clear threadlocal
}
}
Now, the caller has to provide a function and a value. Since the intended method is an instance method, the receiver instance can be treated like a function argument
Then, the function might be again specified either, as a (now unbound) method reference
List<SpecialObject> results=PaginationDecorator.withPaging(
SpecialService::getSpecialObjs, specialService, pageSize, pageNumber);
or a lambda expression:
List<SpecialObject> results=PaginationDecorator.withPaging(
ss -> ss.getSpecialObjs(), specialService, pageSize, pageNumber);
*There is an alternative to both, resorting to AutoCloseable and try-with-resource, rather than try…finally. Define the helper class as:
interface Paging extends AutoCloseable {
void close();
static Paging withPaging(int pageSize, int pageNumber) {
PaginationKit.setPaginationInput(pageSize, pageNumber);
return ()->PaginationKit.clearPaginationInput();
}
}
and use it like
List<SpecialObject> results;
try(Paging pg=Paging.withPaging(pageSize, pageNumber)) {
results=specialService.getSpecialObjs();
}
The advantage is that this will not break the code flow regarding your intended action, i.e. unlike lambda expressions you may modify all local variables inside the guarded code. Recent IDEs will also warn you if you forget to put the result of withPaging inside a proper try(…) statement. Further, if an exception is thrown and another one occurs inside the cleanup (i.e. clearPaginationInput()), unlike finally, the secondary exception will not mask the primary one but get recorded via addSuppressed instead.
That’s what I would prefer here.
A: Your second approach seems cleaner and easier for this task. As for implementation you can just use Java's Proxy class. It seems easy enough. I don't know any libraries that somehow make it even more easier.
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class PagingDecorator {
public static void setPaginationInput(int pageSize, int pageNumber) {
}
public static void clearPaginationInput() {
}
public static <T> T wrap(final Class<T> interfaceClass, final T object, final int pageSize, final int pageNumber) {
if (object == null) {
throw new IllegalArgumentException("argument shouldn't be null");
}
ClassLoader classLoader = object.getClass().getClassLoader();
return (T) Proxy.newProxyInstance(classLoader, new Class[]{interfaceClass}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
setPaginationInput(pageSize, pageNumber);
try {
return method.invoke(object, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw e;
} finally {
clearPaginationInput();
}
}
});
}
public static <T> T wrap(final T object, final int pageSize, final int pageNumber) {
if (object == null) {
throw new IllegalArgumentException("argument shouldn't be null");
}
Class<?>[] iFaces = object.getClass().getInterfaces();
//you can use all interfaces, when creating proxy, but it seems cleaner to only mock the concreate interface that you want..
//unfortunately, you can't just grab T as interface here, becuase of Java's generics' mechanic
if (iFaces.length != 1) {
throw new IllegalArgumentException("Object implements more than 1 interface - use wrap() with explicit interface argument.");
}
Class<T> iFace = (Class<T>) iFaces[0];
return wrap(iFace, object, pageSize, pageNumber);
}
public interface Some {
}
public static void main(String[] args) {
Some s = new Some() {};
Some wrapped1 = wrap(Some.class, s, 20, 20);
Some wrapped2 = wrap(s, 20, 20);
}
}
A: You are using Java 8, right? Maybe you can add a default method without any implementation (sounds a litte weird, I know) like this:
// Your current service interface
interface ServiceInterface <T> {
// Existing method
List<T> getObjects();
// New method with pagination atributes
default List<T> getObjects(int pageSize, int pageNumber) {
throw new UnsupportedOperationException();
}
}
The new services (with pagination suport) must override this method. In my opinion, this way You "keep it simple". | unknown | |
d12362 | train | You could achieve this with what I would call a pythonic one-liner.
We don't need to bother with using a regex, as we can use the built-in .count() method, which will from the documentation:
string.count(s, sub[, start[, end]])
Return the number of (non-overlapping) occurrences of substring sub in string s[start:end]. Defaults for start and end and interpretation of negative values are the same as for slices.
So all we need to do is sum up the occurrences of each keyword in kwlist in the string ltxt. This can be done with a list-comprehension:
output.write(str(sum([ltxt.count(kws) for kws in kwlist])))
Update
As pointed out in @voiDnyx's comment, the above solution writes the sum of all the counts, not for each individual keyword.
If you want the individual keywords outputted, you can just write each one individually from the list:
counts = [ltxt.count(kws) for kws in kwlist]
for cnt in counts:
output.write(str(cnt))
This will work, but if you wanted to get silly and put it all in one-line, you could potentially do:
[output.write(str(ltxt.count(kws))) for kws in kwlist]
Its up to you, hope this helps! :)
If you need to match word boundaries, then yes the only way to do so would be to use the \b in a regex. This doesn't mean that you cant still do it in one line:
[output.write(str(len(re.findall(r'\b'+re.escape(kws)+r'\b'))) for kws in kwlist]
Note how the re.escape is necessary, as the keyword may contain special characters. | unknown | |
d12363 | train | here is my suggestion:
ul {
list-style: none;}
A: the list-style properties apply to elements with display: list-item only ,make sure your list elements doesnt have any other display style.UPDATE
seeing your link your style.css file is overriding your custom style with list-style-type: disc; you have to get rid of this line.
UPDATE 2use this code in your custom css .entry-content ul > li {
list-style-type: none !important;
}
this will do the job quickly. | unknown | |
d12364 | train | Cat:
allOf:
- $ref: "#/definitions/Animal"
- type: "object"
properties:
declawed:
type: "boolean"
Animal:
type: "object"
required:
- "className"
discriminator: "className"
properties:
className:
type: "string"
color:
type: "string"
default: "red"
You need add code at parent class
required:
- "className" | unknown | |
d12365 | train | You can first define a two column coordinate-matrix of the values you want to replace, where the first column refers is the row-index and the second column is the column-index. As an example, suppose you want to replace the cells c(2,1), c(2,2) and c(1,2) in a 3x3 matrix B with the calues from a 3x3 matrix A:
ind <- cbind(c(2,2,1), c(1,2,2))
A <- matrix(1:9, ncol = 3)
B <- matrix(NA, ncol = 3, nrow = 3)
B[ind] <- A[ind]; A[ind] <- 0
B
[,1] [,2] [,3]
[1,] NA 4 NA
[2,] 2 5 NA
[3,] NA NA NA
A
[,1] [,2] [,3]
[1,] 1 0 7
[2,] 0 0 8
[3,] 3 6 9 | unknown | |
d12366 | train | Chrome's .apk
Firefox's .apk
Download both .apk files and install to your AVD using adb install apk_name
A: To install something onto a device, you need to already have the device running.
So first, start the device using the emulator command.
Then, in a different terminal/command window, use the adb command to install the package. In my case, I've copied the apk file to the platform-tools folder:
./adb install Firefox_17.0.apk
Like the rest of the emulator, the installation is slow, so be patient.
Of course, this just installs the packages. Getting them to run successfully is another matter entirely. So far, I cannot get the Chrome or Firefox packages to run. Chrome says "Not supported on this version of Android. Version 4.0 is minimal supported version." I am running 4.3 in the emulator. And Firefox starts but then immediately terminates with a "Unfortunately, Firefox has stopped" message.
A: Get the apk files and install them through adb (adb install .apk. | unknown | |
d12367 | train | What you are doing here is copying the whole screen and draw it at coordinate Rect(442,440,792,520); in your new bitmap... Which is off its canvas.
The coordinate Rect(442,440,792,520) correspond to the part you want to get from the source bitmap. You want to copy it "inside" your new bitmap, so within the rect Rect(0,0,350,80)
You can simply adjust your rect like this :
rect_source := Rect(442,440,792,520);
rect_destination := Rect(0,0,350,80);
The rest of your code seems correct. | unknown | |
d12368 | train | You don't have to use ? as the binding placeholder, you can use :names and an associative array. You can then pass the associative array as the binding list and PDO will now to match the keys of the array with the :binding_names. For example, with an associative array, if the keys match the fields in the database, you can do something like this:
$data = array('one'=>'Cathy', 'two'=>'9 Dark and Twisty Road', 'three'=>'Cardiff');
$fields = array_keys($data);
$field_str = '`'.implode('`,`',$fields).'`';
$bind_vals = ':'.implode(',:',$fields);
$sql = 'INSERT INTO tablename ('.$field_str.') VALUES ('.$bind_vals.')';
$sth = $dbh->prepare($sql);
$sth->execute($data);
That will handle an unknown number of name/value pairs. There is no getting around not knowing what field names to use for the insert. This example would also work with ? as the binding placeholder. So instead of names, you could just repeat the ?:
$bind_vals = str_repeat('?,', count($data));
$sql = 'INSERT INTO tablename ('.$field_str.') VALUES ('.$bind_vals.')';
A: Prepared statements only work with literals, not with identifiers. So you need to construct the SQL statement with the identifiers filled in (and properly escaped).
Properly escaping literals is tricky, though. PDO doesn't provide a method for doing literal-escaping, and MySQL's method of escaping literals (using `) is completely different from every other database and from the ANSI SQL standard. See this question for more detail and for workarounds.
If we simplify the issue of escaping the identifiers, you can use a solution like this:
// assuming mysql semantics
function escape_sql_identifier($ident) {
if (preg_match('/[\x00`\\]/', $ident)) {
throw UnexpectedValueException("SQL identifier cannot have backticks, nulls, or backslashes: {$ident}");
}
return '`'.$ident.'`';
}
// returns a prepared statement and the positional parameter values
function prepareinsert(PDO $pdo, $table, $assoc) {
$params = array_values($assoc);
$literals = array_map('escape_sql_identifier', array_keys($assoc));
$sqltmpl = "INSERT INTO %s (%s) VALUES (%s)";
$sql = sprintf($sqltmpl, escape_sql_identifier($table), implode(',',$literals), implode(',', array_fill(0,count($literals),'?'));
return array($pdo->prepare($sql), $params);
}
function prefixkeys($arr) {
$prefixed = array();
for ($arr as $k=>$v) {
$prefixed[':'.$k] = $v;
}
return $prefixed;
}
// returns a prepared statement with named parameters
// this is less safe because the parameter names (keys) may be vulnerable to sql injection
// In both circumstances make sure you do not trust column names given through user input!
function prepareinsert_named(PDO $pdo, $table, $assoc) {
$params = prefixkeys($assoc);
$literals = array_map('escape_sql_identifier', array_keys($assoc));
$sqltmpl = "INSERT INTO %s (%s) VALUES (%s)";
$sql = sprintf($sqltmpl, escape_sql_identifier($table), implode(',',$literals), implode(', ', array_keys($params)));
return array($pdo->prepare($sql), $params);
} | unknown | |
d12369 | train | #!/usr/bin/python
from subprocess import Popen, PIPE, call
s_REG=raw_input('Please enter Reg number: ')
a = Popen(["grep -l %s /shares/MILKLINK/PPdir/*/*.dpt" %s_REG],shell=True, stdout = PIPE)
FILE_DIR = a.communicate()[0]
FILE_DIR=FILE_DIR.rstrip('\n')
FILE=open("%s" %FILE_DIR , 'r')
# Read File into array
LINES = FILE.read().split('\n')
# Remove Blank Lines and whitespace
LINES = filter(None, LINES)
# Ignore any lines that have been commented out
LINES = filter(lambda x: not x.startswith('#'), LINES)
FILE.close()
# Call the CrossRef Processor for each Reg to make sure for no differences
for I in range(len(LINES)):
call(["/shares/optiload/prog/indref.sh", "%s" %LINES[I]]) | unknown | |
d12370 | train | WebSecurity uses different dbContext
, you need to use the same dbContext, which is used to create the database tables. you can check it out in the web.config file for the connectionstring.. and use the exact dbContext
Add this in AuthConfig.cs
WebSecurity.InitializeDatabaseConnection(
"specifyTheDbContextHere",
"UserProfile",
"UserId",
"UserName",
autoCreateTables: true
); | unknown | |
d12371 | train | You can use std::vector constructor
explicit vector (size_type n, const value_type& val = value_type(),
const allocator_type& alloc = allocator_type());
next way
vector<double> myVector;
double value = 1.;
myVector = vector<double>(1200, value);
alternative is std::fill, which will avoid memory allocation
std::fill(begin(myVector), end(myVector), value);
A: You could use loop unrolling:
std::vector<double> my_vector(1200);
for (int i = 0; i < 300; i += 4)
{
my_vector[i + 0] = value;
my_vector[i + 1] = value;
my_vector[i + 2] = value;
my_vector[i + 3] = value;
}
I suggest playing around with the number of assignments in the loop. The idea here is to reduce the overhead of incrementing and branching (do more data operations). | unknown | |
d12372 | train | I ended up checking the attachment to stage and visibility manually on an interval. Advantage is that it's now also pretty easy to calculate the total alpha if I would ever need that.
private _handleInterval():void {
let addToStage:boolean = false;
let p:PIXI.DisplayObject = this; // 'this' is an extension of a PIXI.Container
while (p != null && p.visible) {
if (p.parent === this.stage) {
addToStage = true;
break;
}
p = p.parent;
}
}
Not the most elegant solution since I would have preferred a pure Pixi solution but it gets the job done :)
If anyone has a better suggestion feel free to post a new answer! | unknown | |
d12373 | train | My solution was simple.
I just increased the z-index even more.
.pac-container { z-index: 9999 !important; } | unknown | |
d12374 | train | It's perfectly fine to write
@RequestMapping("/news/feed/featurednews/{feedname}")
public List<NewsModel> getFeed(String feedname, @RequestParam("start", optional) Integer startIndex) {
return feedService.getFeaturedNewsByName(feedname);
}
@RequestMapping("/news/{newsPageName}")
public String goToNewsPage(Model m, String newsPageName) {
m.addAttribute("stories", this.getFeed(newsPageName, 0));
return getGenericNewsViewName();
}
The Controller by itself is a plain Java class, you just tell the Spring request dispatcher on where to map requests to using the annotations (which doesn't affect any normal method call). | unknown | |
d12375 | train | One of the options is to turn Set terms into List terms, that makes GORM delete and re-create the collection upon every save() | unknown | |
d12376 | train | You are using the same field for operator and value in the struct Node_t. Extend your struct as this:
typedef struct Node_t {
int value;
char op; /*operator*/
struct Node_t *left;
struct Node_t *right;
} Node, *Node_p;
Add a new parameter to the function setNode for the operator (set it to '\0' when Node is a number; you must do the switch of eval over this operator), and add
case '\0':
return np->value;
break;
to the switch of eval. | unknown | |
d12377 | train | This problem haven't solves for long time
discussions.apple.com/message/23671694
A: It is due to the scrollbar that appears on the iframe due to the length of the form in the viewport. If you do not have anything else on the page other than the iframe, turn the body's scroll bar off by using body { overflow: hidden } | unknown | |
d12378 | train | The simplest way to achieve parity in both modes (and potentially across platforms) might be to override the button's default style with your own.
You can look into the default button style template, make a copy in you apps resources, and change the colors used to from default staticresource or dynamicresource to your desired color palette. | unknown | |
d12379 | train | This can be accomplished more succinctly via slicing:
op_list = ip_list[:1]
If ip_list has at least one element, op_list will be a singleton list with the first element of ip_list. Otherwise, op_list will be an empty list.
>>> a = [1, 2, 3]
>>> b = []
>>> a[:1]
[1]
>>> b[:1]
[]
A: op_list = [] if ip_list else [ip_list[0]]
A: You only need the first element if ip_list has any.
Here is one of the easiest solution for that:
[ip_list[0]] if ip_list else [] | unknown | |
d12380 | train | Sorry, got it myself. Like explained here:
https://intellitect.com/calling-web-services-using-basic-authentication/ | unknown | |
d12381 | train | With a few tweaks to what I was setting I got this working just fine, would still be interested in other peoples' views on how they do it. | unknown | |
d12382 | train | You're using the wrong key in PHP
You're calling these keys:
$customerName = mysqli_real_escape_string( $db->con, trim( $data['customerName'] ) );
$customerPhone = mysqli_real_escape_string( $db->con, trim( $data['phone'] ) );
$customerEmail = mysqli_real_escape_string( $db->con, trim( $data['email'] ) );
$customerAddress1 = mysqli_real_escape_string( $db->con, trim( $data['addressLine1'] ) );
$customerAddress2 = mysqli_real_escape_string( $db->con, trim( $data['addressLine2'] ) );
but you should be calling:
$customerName = mysqli_real_escape_string( $db->con, trim( $data['customerName'] ) );
$customerPhone = mysqli_real_escape_string( $db->con, trim( $data['customerPhone'] ) );
$customerEmail = mysqli_real_escape_string( $db->con, trim( $data['customerEmail'] ) );
$customerAddress1 = mysqli_real_escape_string( $db->con, trim( $data['customerAddress1'] ) );
$customerAddress2 = mysqli_real_escape_string( $db->con, trim( $data['customerAddress2'] ) );
To fix this just copy and paste (replace) the variable assignment in the SQL code. | unknown | |
d12383 | train | If you have an option to construct/concat a String prior to run the query, there is no problem:
public String methodOne(String firstOperator
, String secondOperator) {
return "select * from table_name where column_name1 "
+ firstOperator + " ?1 and column_name2 "
+ secondOperator +" ?2";
}
It is more complicated if you use SpringData repositories.
There isn't a lot you can do with native queries parameters because SpringData is looking for native SQL operators inside the query string. But you can try to do some tricks with LIKE operator and built-in functions (in SQL, sometimes >,< can be replaced with LIKE)
(not completely an answer to your question, but)
A condition that can be omitted
@Query(value =
... AND column_name LIKE IIF(:myParam <> '%', :myParam,'%')
<skipped>
... repositoryMethod(@Param("myParam") String myParam);
IIF - a ternary operator function in MSSQL, you can find something like this in your RDBMS
when you send myParam='actualValue' it will be transformed into
and column_name LIKE 'actualValue'
i.e. column_name='actualValue'
when you send myParam='%' it will be transformed into
and column_name LIKE '%'
i.e. "and TRUE" | unknown | |
d12384 | train | After taking appropriate permissions for the background notifications in your app and adopting UNUserNotificationCenterDelegate in the appropriate viewController. You can implement this method to trigger notifications in the background and take actions to perform any action from the notification. To perform any action from the notification you need to adopt the function userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void).
func startNotifications() {
let notificationCenter = UNUserNotificationCenter.current()
// to include any action in the notification otherwise ignore it.
let action = UNNotificationAction(identifier: "ActionRelatedIdentifier", title: "Name which you want to give", options: [.destructive, .authenticationRequired])
let category = UNNotificationCategory(identifier: "CategoryName", actions: [stopAction], intentIdentifiers: [], options: [])
notificationCenter.setNotificationCategories([category])
let content = UNMutableNotificationContent()
content.title = "Your Title"
content.body = "Message you want to give"
content.sound = UNNotificationSound.default
// To trigger the notifications timely and repeating it or not
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1.5, repeats: false)
content.categoryIdentifier = "CategoryName"
print("Notifications Started")
let request = UNNotificationRequest(identifier: "NotificationRequestIdentifier", content: content, trigger: trigger)
notificationCenter.add(request, withCompletionHandler: { (error) in
if error != nil {
print("Error in notification : \(error)")
}
})
}
Disclaimer: do apply the solution according to your need and ask if anything wrong happens. This code is for triggering background notifications. | unknown | |
d12385 | train | To click on the drop down menu and select the menu item with text as MIL you need to induce WebDriverWait for the element_to_be_clickable() and you can use the following xpath based Locator Strategies:
*
*Using XPATH:
driver.get('https://tradenba.com/trade-machine')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='select-idTeam1Desktop']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='MuiListItemText-root MuiListItemText-inset']/span/div/p[text()='MIL']"))).click()
*Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
*Browser Snapshot: | unknown | |
d12386 | train | There's no guarantee that $res->filename(); will produce a file extension or anything at all for that matter. The page you're currently reading doesn't have a filename extension for example.
You will have to guess a filename extension from the media type.
use MIME::Types qw(by_mediatype);
...
my $filename = $r->filename();
if(!$filename) { $filename = 'untitled'; }
if($filename !~ /\.[a-zA-Z0-9]{1,4}$/) {
my $type = $res->header('Content-Type');
my $ext = 'txt';
if($type) {
my @types = by_mediatype($type);
if($#types > -1) {
$ext = $types[0][0];
}
}
$filename .= '.' . $ext;
}
print $filename; | unknown | |
d12387 | train | To make the client applications debugable, create a new tiny project and set both the service and the client application as dependencies. The only file it should contain is Program.cs, and its only function should look like this:
[STAThread]
static void Main(string[] args)
{
new System.ServiceModel.ServiceHost(typeof(MyServiceClass)).Open();
MyClientApplication.Program.Main(args);
}
And then merge the app.config for both into a single app.config for this tiny application. But now the service is hosted inside the same process as the client, and they can both be debugged interchangeably.
This allows removing the AutoStart feature from the service, but still run the client application together with the service. | unknown | |
d12388 | train | There are some tools in Twisted that will help you do this more easily. For example, cooperate:
from twisted.internet.task import cooperate
def generate_update_deferreds(collection, many_docs):
for doc in update_docs:
d = collection.update({'_id': doc['_id']}, doc, upsert=True)
yield d
work = generate_update_deferreds(...)
worker_tasks = []
for i in range(count):
task = cooperate(work)
worker_tasks.append(task)
all_done_deferred = DeferredList([task.whenDone() for task in worker_tasks]) | unknown | |
d12389 | train | Try removing the call to setSingleLine. And use setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE). It'd also put this call before the setMaxLines and setLines call to be sure.
Note: setLines overrides the settings of setMaxLines and setMinLines.
The TextView has many issues surrounding the various calls to how it should display multiple, ellipses, etc.
A: The setSingleLine(false) seemes to reset the setMaxLines command. Try to move the setSingleLine command before the setText. That worked for me.
A: The below code is working fine for me
txt = (TextView)findViewById(R.id.textview);
txt.setMaxLines(5);
txt.setMovementMethod(new ScrollingMovementMethod());
txt.setScrollContainer(true);
txt.setText("Example Text");
txt.setTextColor(Color.WHITE);
txt.setScrollbarFadingEnabled(true);
in xml inside textview
android:scrollbars="vertical" | unknown | |
d12390 | train | That page is probably using the_date() function.
If so, modify it using format parameter to something like this:
the_date('d/m/Y');
Check also this Codex page about formatting the date and time. | unknown | |
d12391 | train | Fixed with sudo rm -rf /opt/flutter/.git/FETCH_HEAD | unknown | |
d12392 | train | yes.
from sqlalchemy import create_engine
from sqlalchemy.engine import reflection
engine = create_engine('...')
insp = reflection.Inspector.from_engine(engine)
for name in insp.get_table_names():
for index in insp.get_indexes(name):
print index | unknown | |
d12393 | train | Lambda functions are a language construct of defining a function.
LINQ is a library of functions. Many of these functions takes functions as parameters to compare or select elements from your lists. Therefore it is very common to use lambda functions to specify these parameter functions. Simple because that makes puts the definition of what it is supposed to do where you actually use it. But there is nothing preventing you from NOT using lambda functions with LINQ. | unknown | |
d12394 | train | Not only it is possible, but it's been done numerous times. There are several open and closed source solutions available. A quick github search gave me this one.
https://github.com/RReverser/mpegts
EDIT: New/better option just released
http://engineering.dailymotion.com/introducing-hls-js/ | unknown | |
d12395 | train | To replace IPython.config.cell_magic_highlight, you can use something like
import IPython
js = "IPython.CodeCell.config_defaults.highlight_modes['magic_fortran'] = {'reg':[/^%%fortran/]};"
IPython.core.display.display_javascript(js, raw=True)
so cells which begin with %%fortran will be syntax-highlighted like FORTRAN. (However, they will still be evaluated as python if you do only this.)
A: For recent IPython version, the selected answer no longer works. The 'config_default' property was renamed options_default (Ipython 6.0.0).
The following works:
import IPython
js = "IPython.CodeCell.options_default.highlight_modes['magic_fortran'] = {'reg':[/^%%fortran/]};"
IPython.core.display.display_javascript(js, raw=True) | unknown | |
d12396 | train | This won't work since the Input:checkbox is INSIDE the <label>. Browsers will set focus on the input upon a click on the label.
A: An input element inside an a violates common sense as well as HTML5 CR. Nesting two interactive elements raises the issue which element is activated on mouse click.
Instead of such construct, use valid and sensible HTML markup. Then please formulate the styling question in terms of desired or expected rendering vs. actual rendering, instead of saying that “this” “does not work”. | unknown | |
d12397 | train | One of the solution is to implement an interceptor service where you can format multipart/form-data response.
For example, your inteceptor will be - multipart.interceptor.ts :
@Injectable()
export class MultipartInterceptService implements HttpInterceptor {
private parseResponse(response: HttpResponse<any>): HttpResponse<any> {
const headerValue = response.headers.get('Content-Type');
const body = response.body;
const contentTypeArray = headerValue ? headerValue.split(';') : [];
const contentType = contentTypeArray[0];
switch (contentType) {
case 'multipart/form-data':
if (!body) {
return response.clone({ body: {} });
}
const boundary = body?.split('--')[1].split('\r')[0];
const parsed = this.parseData(body, boundary); // function which parse your data depends on its content (image, svg, pdf, json)
if (parsed === false) {
throw Error('Unable to parse multipart response');
}
return response.clone({ body: parsed });
default:
return response;
}
}
// intercept request and add parse custom response
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(customRequest).pipe(
map((response: HttpResponse<any>) => {
if (response instanceof HttpResponse) {
return this.parseResponse(response);
}
})
);
}
} | unknown | |
d12398 | train | So if I understand correctly, the question is "How do I extract HTML embedded in javascript code".
The quick and dirty solution is to use a regular expression to extract the HTML. This is going to be a little finicky because of quoting but it's not too bad, you need a regular expression which can match a string with escaped quotes, this one will do the trick for doublequotes, it will match anything between doublequotes which is not a double quote, or is a quoted double quote:
"((?:[^"]+|\\")+)"
You can then use that to create a regular expression which will extract the contents of the html string from it's jquery wrapping:
import re
mixed_js_html = r'$(".entry:last").after("<div class=\"entry\"><p>some data</p></div>");')
m = re.search(r'after\("((?:[^"]+|\\")+)"\)', mixed_js_html):
html_code = m.group(1)
html_code = html_code.replace('\\"', '"') # unescape quotes
print(html_code)
# <div class="entry"><p>some data</p></div> | unknown | |
d12399 | train | Container's volumes won't be saved when you commit a container as an image. So you can take advanced of this to exclude a folder (volume) from the snapshot. For example, suppose you want to exclude dir /my-videos from your image when committing. You can run your container mounting /my-videos as a volume:
docker run -i -t -v /my-videos my_container /bin/bash
or you mount a host's folder in container's /my-videos:
docker run -i -t -v /home/user/videos:/my-videos my_container /bin/bash | unknown | |
d12400 | train | nums.size() return a unsigned value,-2 cause overflow.
(int)nums.size()-2 can solve it.
A: The problem is that the size() function returns an unassigned int, and you're comparing it to i, which is a signed int.
Turn this line...
for (int i = 0; i < nums.size() - 2; i++) {
Into this...
for (int i = 0; i < ((int)nums.size()) - 2; i++) {
And here's a link to someone else with a similar problem, if you wanna read more about other solutions...
What is wrong with my For loops? i get warnings: comparison between signed and unsigned integer expressions [-Wsign-compare] | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.