text:
Q: Redirect if iOS, Android or Windows Phone I need a little bit of help here. I need help with a script. I try:
<script language=javascript>
<!--
if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
    location.replace("http://url-to-send-them/iphone.html");
}
-->
</script>

But is not working as I expected. I need to redirect to different stores if I go to one URL example. If i go to: www.mydomain.com.ar/app and I use an Android Phone I need to redirect my browser to the Android Play Store. If I go to www.mydomain.com.ar/app and I use iOS I need to redirect to the App Store. How can i do this? I dont have the knowledge so if you can help me will be great. Thank you so much.

A: This should work.
var isMobile = {
    Android: function() {
        return /Android/i.test(navigator.userAgent);
    },
    iOS: function() {
        return /iPhone|iPad|iPod/i.test(navigator.userAgent);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
    }
};


text:
Q: How does NPM/Node.js do path resolution in the local node_modules/.bin directory Been confused about this for awhile
I have an executable file (cli/exec.js) in an NPM module called "foo" like so:
/foo
--/cli
   exec.js
--/lib
package.json

in package.json, we have:
  "name": "foo",
  "bin": {
    "exec-foo": "cli/exec.js"
  }

when this module gets installed, with npm install, node_modules looks like this:
--/node_modules
---/.bin
    exec-foo
---/foo
---/lodash
---/async
---/whatev

.........
...What confuses the crap out of me: how does Node.js do module/dependency resolution with the require function, now that the exec-foo.js file is no longer where it once was in the project, but is now located in node_modules/.bin? Is there a simple explanation for this?

A: NodeJS resolution is pretty well explained in the documentation.

If the module identifier passed to require() is not a native module, and does not begin with '/', '../', or './', then Node.js starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location. Node will not append node_modules to a path already ending in node_modules.

In your case node_modules/.bin/exec.js will be a symbolic link - a pointer to the original file.
Then NodeJS checks the original file path and starts parsing the required modules. If it can't find in the current node_modules path goes 1 directory upwards until it finds your library.
If no library has been found it throws an error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Netty ChannelRead() was not invoked and writeAndFlush() not work I implemented RPC using Netty, however, channelRead() in RPCClientHandler.java could not be invoked. Additionally, writeAndFlush() also not worked in call() of RPCClientHandler.java unless I invoked writeAndFlush() again somewhere else, for example, in ServiceProxy.java. I guess there might be something wrong in ServiceProxy.java of the Client Side.
Client Side
RPCClient.java
package rpc.client;
//omit import

public class RPCClient {
public String methodA(String message){
    String protocol="send?";
    IUserService s = (IUserService) new ServiceProxy().getProxy(IUserService.class, protocol);
    return s.say(message);
}

public static void main(String[] args) {
    System.out.println("client result:"+new RPCClient().methodA("Aloha")); //not print
    System.out.println("client result:"+new RPCClient().methodA("Ola")); //not print
}
}

RPCClientHandler.java
package rpc.clientstub;
//omit import

 public class RPCClientHandler extends ChannelInboundHandlerAdapter implements Callable {
private ChannelHandlerContext context;
private String response;
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    context = ctx;
}

@Override
public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    System.out.println("invoked success"); // not print
    response = msg.toString();
    System.out.println("invoked success"+response); //not print also
    notify();
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.close();
}

}
public synchronized Object call() throws Exception {
    ChannelFuture cf = context.writeAndFlush("Ack");
    System.out.println(cf);  //print:DefaultChannelPromise@113904e2(incomplete)
    System.out.println("invoked1, ctx is: "+context); //print
    wait();
    System.out.println("invoked2"); //not print
    return response;
}
}

ServiceProxy.java
package rpc.clientstub;
//omit import here

public class ServiceProxy {
private static ExecutorService executor
        = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private static RPCClientHandler clientHandler;

public Object getProxy(Class<?> serviceClass, String protocol){
    return Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if(clientHandler == null) {
                        startClient();
                        System.out.println("clientHandler exists:" + clientHandler);
                    }
                    return executor.submit(clientHandler).get();

                }
            });
    }

public static void startClient() throws Exception{
    clientHandler = new RPCClientHandler();
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    try{
        bootstrap.group(group)
                 .channel(NioSocketChannel.class)
                 .handler(new ChannelInitializer<SocketChannel>() {
                     @Override
                     protected void initChannel(SocketChannel ch) throws Exception {
                         ch.pipeline().addLast(new StringDecoder());
                         ch.pipeline().addLast(new StringEncoder());
                         ch.pipeline().addLast(clientHandler);
                     }
                 });
        ChannelFuture cf = bootstrap.connect("127.0.0.1", 8890).sync();
        cf.channel().writeAndFlush("DDD");  //for example, only I invoked writeAndFlush here, message could be seen from server side

    } finally{
        group.shutdownGracefully();
    }

}
}

Server Side
RPCServer.java
public class RPCServer {
public static void main(String[] args)  {
    startServer();
}
public static void startServer() {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try{
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup)
                       .channel(NioServerSocketChannel.class)
                       .childHandler(new ChannelInitializer<SocketChannel>() {
                           @Override
                           protected void initChannel(SocketChannel ch) throws Exception {
                               ch.pipeline().addLast(new StringDecoder());
                               ch.pipeline().addLast(new StringEncoder());
                               ch.pipeline().addLast(new RPCServerHandler());
                           }
                       });
        ChannelFuture cf = serverBootstrap.bind(8890).sync();
        System.out.println("provider is running");
        cf.channel().closeFuture().sync();
    } catch (Exception e){
        e.printStackTrace();
    } finally{
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
}

RPCServerHandler.java
public class RPCServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    System.out.println("msg in channelRead:" + msg +"the class of msg is:" + msg.getClass());
    if(msg.toString().startsWith("send?")){
            String res = new UserServiceImpl().say(msg.toString().substring(msg.toString().lastIndexOf("?")+1));
            ctx.writeAndFlush(res);
    }
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.close();
}
}

UserServiceImpl.java
public class UserServiceImpl implements IUserService {
public String say(String message){
   System.out.println("called");
   if(message != null){
       return "##RECEIVED MESSAGE from client:"+message;
   } else{
       return "##RECEIVED NOTHING";
   }
}
}


text:
Q: How can I scan strings with spaces in them using scanf()? I want to write a sub-program in which a user can input their comment.
I use scanf("%s", X) and let them input a comment, but it can only store the word before a space bar in the string.
How can I solve this problem in order to store a whole sentence into a string or a file?
My code is presented below:
FILE *fp;
char comment[100];
fp=fopen("comment.txt","a");
printf("You can input your comment to our system or give opinion to the musics :\n");
scanf("%s",comment);
fputs(comment,fp);

A: instead of scanf use fgets on stdin in order to read the whole line.

A: Rather than the answers that tell you not to use scanf(), you can just the the Negated scanset option of scanf():
scanf("%99[^\n]",comment); // This will read into the string: comment
                           // everything from the next 99 characters up until
                           // it gets a newline

A: scanf() with %s as format specifier reads a sequence of characters starting from the first non-whitespace character until (1) another whitespace character or (2) upto the field width if specified (e.g. scanf("%127s",str); -- read 127 characters and appends null byte as 128th), whichever comes first. And then automatically append null byte at the end. The pointer passed my be large enough to hold the input sequence of characters.
You can use fgets to read the whole line:
fgets(comment, sizeof comment, stdin);

Note that fgets reads the newline character as well. You may want to get rid of the newline character from the comment.

A: You can make use of gets(), getline() functions to read string from stdin.


text:
Q: Get specific columns who contains specific text I have an string array like this:
string[] tooltipstring

this array contain data like:

I want to know how can I select data depending of what text say.. for example I want to get only objects who have progress to backcheck then concat them and I should get:
- Median progress to backcheck = 0 minutes - Average progress to backcheck = 12 minutes

How can I achieve that? Regards

A: You can use Linq and string.Join
using System.Linq;

string[] result = tooltipstring
                    .Where(tt => tt.Contains("progress to backcheck"))
                    .ToArray();

string finalResult = string.Join(" ", result);

A: using System.Linq;

string result = "- " + string.Join(" - ", tooltipstring.Where(x => x.Contains("progress to backcheck"));


text:
Q: ASP.NET MVC 3 project in Xamarin gives System.UnauthorizedAccessException error I run Xamarin (4.0.10 build 5) on Mac OS X (10.9). I created ASP.NET MVC 3 project. First run gave error with Microsoft.AspNet.WebPages. I solved this issue following this article and fixed it. Now when I run it gives another error:

System.UnauthorizedAccessException Access to the path "/Library/Frameworks/Mono.framework/Versions/3.2.0/etc/mono/registry"
  is denied.
Stack trace:
at System.IO.Directory.CreateDirectoriesInternal (System.String path)
  [0x00064] in
  /private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin-no-pcl/build-root/mono-3.2.0/mcs/class/corlib/System.IO/Directory.cs:113    at System.IO.Directory.CreateDirectory (System.String path) [0x000a4]
  in
  /private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin-no-pcl/build-root/mono-3.2.0/mcs/class/corlib/System.IO/Directory.cs:80
  at System.IO.DirectoryInfo.Create () [0x00000] in
  /private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin-no-pcl/build-root/mono-3.2.0/mcs/class/corlib/System.IO/DirectoryInfo.cs:141
  at (wrapper remoting-invoke-with-check) System.IO.DirectoryInfo:Create
  ()   at System.IO.Directory.CreateDirectoriesInternal (System.String
  path) [0x00039] in
  /private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin-no-pcl/build-root/mono-3.2.0/mcs/class/corlib/System.IO/Directory.cs:98
  at System.IO.Directory.CreateDirectory (System.String path) [0x000a4]
  in
  /private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin-no-pcl/build-root/mono-3.2.0/mcs/class/corlib/System.IO/Directory.cs:80
  at Microsoft.Win32.KeyHandler..ctor (Microsoft.Win32.RegistryKey rkey,
  System.String basedir, Boolean is_volatile) [0x0004a] in
  /private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin-no-pcl/build-root/mono-3.2.0/mcs/class/corlib/Microsoft.Win32/UnixRegistryApi.cs:136

Please help me to solve this issue.

A: On a Linux machine running Arch distribution I made the following changes to make the security issue work:
sudo mkdir /etc/mono/registry
sudo mkdir /etc/mono/registry/LocalMachine
sudo chmod g+rwx /etc/mono/registry/
sudo chmod g+rwx /etc/mono/registry/LocalMachine

A: See if this blog post helps you.
(a crack at a solution)
sudo mkdir /Library/Frameworks/Mono.framework/Versions/Current/etc/mono/registry
sudo chmod g+rwx /Library/Frameworks/Mono.framework/Versions/Current/etc/mono/registry


text:
Q: Website not scrolling on Galaxy S4 and later versions (Android) I'm currently working on a Wordpress site and am having an issue specifically with Galaxy S4 and other versions. It seems to work fine on all other mobile devices, on multiple mobile browsers (Chrome, Safari, etc.) After doing some research I've seen a couple of people having the same issue but no real answer to the problem.
The issue even recreates with emulators built into the desktop browsers, so I have tested it on multiple version of Galaxy using Chromes emulator and the same issue occurs as on the hardware device.
Here is the link to the site I am working on: http://beta.iqcando.com/
I'm truly at a loss as to what could be causing this, as it appears to be fully mobile on other devices. Any suggestions or solutions are welcome, thanks in advance!

A: There is an
overflow-y: hidden!important;

on your html in style.css on line 109.
When you remove that the scroll works fine ;)
If you want to debug your site on mobile, on chrome you can install sdk and then use chrome to inspect the mobile version of your site.
https://developers.google.com/web/tools/chrome-devtools/debug/remote-debugging/remote-debugging


text:
Q: Does driver.findElement(By.className) locate a class that has multiple class names? I've got this HTML:
<class = "abc pqr"></class>

So if I do a driver.findElement(By.className("abc"), will WebDriver actually find the class in the DOM structure?
What I want to know is, does the By.className work if we provide just a substring of the class?

A: The short answer is yes! Either By.className("abc") or By.className("pqr") is perfectly fine in this case.
Note that this is not using a sub-string. In your element <class = "abc pqr"/>, this a space-separated list of classes!

A: If you still need the answer - yes, it will. It will not wok in case if you will try to search it like By.classname("abc pqr") it won't.
If you want to search by part of class use css selector. Imagine you have
<a class="superclass secondaryclass">

Then you can find it with:
By.cssSelector("//a[class*=super]")
as *= is search by substring (not strict one).
If you still want to search by xpath and substring, then you can do some tricks like:
//a[substring(@class, string-length(@class) - 5) = 'super']
Or try to use a[contains(@class, 'super')]
There are too many ways to do it :)

A: Short answer:  no.   You will have to use one of the below methods for selecting an element based on multiple class names.
driver.find(By.cssSelector(".abc.pqr"));

or
driver.find(By.xpath("//*[@class='abc pqr']"));


text:
Q: Is there Function (VB6 or Excel) for convert json date to date format have a good day
i need to create DataBase for exchange rate USD from highcharts
this is json file
i success to extract this file "usd.json" to excel sheet
but the problem how can i convert the column A to Date format
is this possible
this is excel sheet picture
thanks for all

A:
C1 ↓
=TEXT(A1/86400000+DATE(1970,1,1),"mm-dd-e")

Or.  A1 ↓

=TEXT(FILTERXML(""&SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(WEBSERVICE("https://sp-today.com/past/currency/damascus/usd.json"),"[",),"]",),",","")&"","//b["&ROW(A1)*2-1&"]")/86400000+DATE(1970,1,1),"mm-dd-e")

English is not my native language,I am a little hard to understand what you mean, sorry. please excuse typing errors.


text:
Q: Highcharts set global timezone for all charts I'm trying to set my timezone for all charts on my webpage to America/New_York.
I tried many things, using timezoneoffset, timezone with moment.js.
Seems like impossible for me for some reason.
Can someone please help me to set the timezone to the timezone I want, instead of using the client's timezone.
Thank you.


text:
Q: Name of day/month that's not today in another language in php Im trying to get the name of a day in php in another language than English. I changed the locale settings to setlocale(LC_ALL, 'nl_NL'); (this returns true) but the date still shows in English. I then found out you should use strftime() for it to work, but that just returns the current time in the set language, and I'm trying to loop trough a number of predefined days, so the output would be

Vrijdag 30 augustus
Zaterdag 31 augustus
Zondag 1 september

etc.
Subtracting/adding days from the current timestamp is also not an option for what I want to do.

A: Whenever you need to manipulate date/time stamps based on locale, you should use strftime
also change the encoding to utf-8
http://php.net/manual/en/function.strftime.php
example :
<?php
header('Content-Type: text/html; charset=UTF-8');

$myDate = "Feb 21, 2013";

$locale = 'fr_FR.utf8';
setlocale(LC_ALL, $locale);
echo strftime('%d %B %Y', strtotime($myDate));

$locale = 'en_US.utf8';
setlocale(LC_ALL, $locale);
echo strftime('%d %B %Y', strtotime($myDate));
?>

A: strftime was DEPRECATED in PHP 8.1
You can use IntlDateFormatter:
$formatter = new \IntlDateFormatter(
    'nl_NL',
    \IntlDateFormatter::LONG,
    \IntlDateFormatter::LONG,
    'Europe/Amsterdam' //more in: https://www.php.net/manual/en/timezones.europe.php
);

echo $formatter->formatObject(new \DateTime(), "eeee dd MMMM", "nl_NL");

Result:

woensdag 21 september

*

*note that "eeee" is a format from ICU

A: The function strftime takes a second parameter: a unix timestamp:
http://de1.php.net/manual/en/function.strftime.php
You can simply convert your dates to a unix timestamp and pass them as second parameter.


text:
Q: Custom service that connect with Dynamic CRM SDK - Security permission issue Error : System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
When i host my wcf service (service inside Asp.net web application) in Local IIS Server, it is working fine. But when i hosted it in hostgator.com, it gives above error.
Please help me

A: Short answer: hostgator probably runs your code in partial trust (Sandbox) so yo won't be able to deploy that.


text:
Q: Duplicate Symbols for Architecture in XCode with Qt5.1.0 This is the output from XCode when I try to compile. I have thoroughly checked my header files to verify that I am not including something twice. Does anybody see what else could possibly cause this issue? I've even deleted the project and regenerated it. I don't know what I did that could make this happen. Thanks in advance!
Ld Debug-iphonesimulator/Timecards.app/Timecards normal i386
cd /Users/allenh1/time-flashcards-ios/timecards-ios
setenv IPHONEOS_DEPLOYMENT_TARGET 4.3
setenv PATH "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -arch i386 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator6.1.sdk -L/Users/allenh1/time-flashcards-ios/timecards-ios/Debug-iphonesimulator -L/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator6.1.sdk/System/Library/Frameworks -L/Users/allenh1/Qt/5.1.0/Src/qtbase/lib -L/Users/allenh1/Qt/5.1.0/Src/qtbase/plugins/platforms -F/Users/allenh1/time-flashcards-ios/timecards-ios/Debug-iphonesimulator -filelist /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/Timecards.LinkFileList -Xlinker -objc_abi_version -Xlinker 2 -headerpad_max_install_names -framework UIKit -lz -force_load /Users/allenh1/Qt/5.1.0/Src/qtbase/plugins/platforms/libqios.a -framework UIKit -L/Users/allenh1/Qt/5.1.0/Src/qtbase/lib -framework OpenGLES -L/Users/allenh1/Qt/5.1.0/Src/qtbase/plugins/platforms -lz -lm -Xlinker -no_implicit_dylibs -mios-simulator-version-min=4.3 -framework Foundation -framework QuartzCore -lQt5PlatformSupport -framework CoreFoundation -framework CoreText -framework CoreGraphics -lqiosmain -lQt5Widgets -lQt5Gui -lQt5Core -o /Users/allenh1/time-flashcards-ios/timecards-ios/Debug-iphonesimulator/Timecards.app/Timecards

duplicate symbol __ZplRK12TimecardTimeS1_ in:
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/main.o
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/mainwindow.o
duplicate symbol __ZmiRK12TimecardTimeS1_ in:
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/main.o
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/mainwindow.o
duplicate symbol __ZplRK12TimecardTimeS1_ in:
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/main.o
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/TimeQuestion.o
duplicate symbol __ZmiRK12TimecardTimeS1_ in:
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/main.o
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/TimeQuestion.o
duplicate symbol __ZplRK12TimecardTimeS1_ in:
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/main.o
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/TimecardTime.o
duplicate symbol __ZmiRK12TimecardTimeS1_ in:
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/main.o
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/TimecardTime.o
duplicate symbol __ZplRK12TimecardTimeS1_ in:
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/main.o
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/moc_mainwindow.o
duplicate symbol __ZmiRK12TimecardTimeS1_ in:
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/main.o
    /Users/allenh1/time-flashcards-ios/timecards-ios/Timecards.build/Debug-iphonesimulator/Timecards.build/Objects-normal/i386/moc_mainwindow.o
ld: 8 duplicate symbols for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)


text:
Q: How to get url image when upload with GoogleDriveService I am using google drive as the photo storage of the application after uploading, but I have trouble trying to get the image path after uploading. How can I get the link? This is my code upload
$name = $request->file('thumbnail')->getClientOriginalName();
$image=  $request->file('thumbnail')->storeAs('/', $name, 'google');

If i use Storage::disk('google')->allFiles() . I get the following array
[
  0 => "130JDj2AYUyQd-9ABLHW86wXjtHdIOWdJ"
  1 => "1irMQMcYqnt8DSszOEqPKE5a7D30rib30"
]

I know it is random name, the photos I uploaded. but i need the url of each picture. What should I do ? thanks

A: You can use FilesystemReader::listContents
Storage::disk('google')->listContents();

or
use Illuminate\Support\Facades\Storage;

$url = Storage::disk('google')->url('img.png');

dd($url);

or
You can use the below code.
$disk = Storage::disk('google');
$url = $disk->url('foo.jpg');


text:
Q: How to select one list element from an ordered list? I have a list of video titles. They are clickable links. They are arranged in an ordered list.
function showResults(results) {
    var html = '';
    html = "
";
        $.each(results, function(index,value) {
        html += '
' + value.snippet.title + ')
';        });
        html += "
";
        $('#results').html(html);
});

I can assign an id of videoChoice to ol, li, or a. I get an element by it's id tag like this:
"play number *val" : function(val) {
        var test = document.getElementById('videoChoice');
        test.click();

}

If the id is assigned to li or a, I can use the voice command and the video will play. Problem is, this method returns one specific video in the list. So I moved my id tag to the ol. This returns the full ordered list. Problem is I can't figure out how to select a list element by index number. I know how to select an element from an array by index number, for example, but I seem to need a different method here.
So how does one select a list element from an ordered list?
SOLUTION
As mentioned in the answers, the .eq() Jquery method is a good way to do this. I implemented the method, but had to also specify that it was a link by adding 'a'. This made it clickable.
"play number *val" : function(val) {
        var $ol = $('#videoChoice');
        var li = $ol.find('a','li').eq(val).click();
}

A:
I can't figure out how to select a list element by index number

If this is your issue, you can easily select  a list element using jquery eq() method
eg: FIDDLE
  var firstList =  $('ul#id').find('li').eq(0);

A: If you're trying to select by index, check this out:
https://api.jquery.com/eq-selector/
You can select by index using the eq selector, so if you're trying to select the third item on the list, the selector would be as follows:
var Selection = $('li:eq(2)');

A JSFiddle for your convenience.
https://jsfiddle.net/tyatm27b/


text:
Q: Android: Store Spinner Selected Value I have created a spinner that fill data from database.
Assume, user select item from spinner and press back button.(or any other button in my android app). then user do some other stuffs and came back to screen which user previously select item from spinner. in this occasion spinners selected item should be the item that user previously selected.
How cloud i do this?

A: Shared preferences is not really intended for this.  If you use a shared preference, the saved state may persist across different invocations of the activity - may be what you wanted, or may not be.
A better way is to use the feature intended for saving UI state - override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter, as shown in this answer:
Android adding more save results to Notepad sample


text:
Q: One day I [do something] and another day I [don't] Could somebody help to understand if it is possible to use the phrase in the title in situations when you change you mind on certain subject, for example: "I can't decide on my future career. One day I dream of becoming a doctor, and another day I want to be a pilot." I wonder if I need to use preposition 'on' in this case.
Thanks for your advice.

A: "I can't decide on my future career. One day I dream of becoming a doctor, on another I want to be a pilot." On is necessary, the second day is not, and and is optional.
An alternative way to express that would be the following: "I can't decide on my future career. One day I dream of becoming a doctor, the next a pilot."


text:
Q: How do i change a character in a list with a key in another dictionary within Python? I'm trying to make a function that checks the validity of an ID. The IDs start with A, B, C, or D. And I was having trouble replacing the A, B, C, Ds in the input from the user with the key values in the dictionary. Please Help Me~
For example, if the user inputs A, then the program shall check if A is in the dictionary and if it is then it will replace it with the value of the key, i.e. 10.
Thanks
ID_dict = {"A": 10, "B" : 11, "C" : 12, "D" : 13}

ID = list(raw_input("What is your ID"))

def check_id(ID):

???

A: ID_dict = {"A": 10, "B" : 11, "C" : 12, "D" : 13}

ID = raw_input("What is your ID")

def check_id(ID):
     if ID in ID_dict:
          print "Yes Valid"

A: Is this what you want:
ID = list(raw_input("What is your ID"))
def check_id(ID):
    for a in ID:
        if a.upper() in ID_dict:
            print a.upper() +" is there"
        else:
            print a.upper()+" is not there"

check_id(ID)

output:
What is your IDasde
A is there
S is not there
D is there
E is not there


text:
Q: when does Apache felix perform signature verification of a OSGI bundle .jar file? we have a command in apache felix to install an OSGi bundle i.e "felix:install Jar-file". My query is :Does this command also perform verification(before installing) of contents of jar-file against the signature with which it was signed earliar?
Or do we have any specific command in Apache felix to do the same.
If any above command does not perform verification then do i have to use
"jarsigner -verify jar-file" command provided by jarsigner tool in OSGi framework? if yes then how?
Or
do i have to write/embed some code/API in my own bundle code for verification which might run after installation and before resolving any the bundle's dependencies?if yes then what are those APIs provided by OSGi framework or some OSGi container implementaions(like Apache felix, Apache Ace, Equinox etc)?
Or does it require any configuration to set in OSGi bundle, specifically for signature verification?
please do share your some views.
Thanks


text:
Q: SwiftUI: How to implement paging on user swipe? (Previously used UICollectionView -> paging enabled) Background: I'm converting a project from UIKit to SwiftUI. Currently with UIKit, I have a UICollectionView within a UICollectionView, both with Paging enabled. This allows users to swipe up/down and left/right on cells. Each cell fills the entire screen (similar to TikTok's main UI) and each cell has a lot of data to pull from Firebase, so I do not want to load all items when the first view appears, but rather as each cell will appear (this is the current implementation under UIKit via UICollectionView delegates).
Problem: I can't find a way to enable this "paging" (based on user swiping) in SwiftUI. It's hard to imagine that Apple made this new framework without a Paging feature? If they haven't included this, is there a workaround? Otherwise, is there an easy way to include a UICollectionView into a SwiftUIView?
Any help or workarounds would be nice! Thanks :)

A: SwiftUI 2
It looks like a LazyGrid may be what you need.
Here is a sample code for a vertical grid:
struct ContentView: View {
    let data = (1...1000).map { "Item \($0)" }

    let columns = [
        GridItem(.adaptive(minimum: 80))
    ]

    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns, spacing: 20) {
                ForEach(data, id: \.self) { item in
                    Text(item)
                }
            }
            .padding(.horizontal)
        }
    }
}

You can find more information in these links:

*

*SwiftUI Lazy Grid Tutorial

*Impossible Grids with SwiftUI

*How to position views in a grid using LazyVGrid and LazyHGrid

SwiftUI 1
If you're bound to iOS 13 or LazyGrid just doesn't match your expectations, you can still wrap your UICollectionView in UIViewRepresentable.
See this link for more explanation: Implementing UICollectionView / UICollectionView DiffableDataSource in SwiftUI


text:
Q: What is the use of ("*") in jquery I am reading jQuery, i don't know why use ("*") please explain it's helpful

A: * is a selector in jquery which select everything without any condition including html, head and body.
Here is an example explaining its usage.

$(document).ready(function(){
    $("button").click(function(){
        $("*").hide();
    });
});

  Hello text

<button>Click Me to Hide everything</button>

* selector can be used with elements that it selects all child elements within the specified element. without any condition

$(document).ready(function(){
    $("button").click(function(){
        $("div *").toggle();
    });
});
div{
border:0.5px solid red;
}

Hello text

  Here is a link

<button>Click Me to Hide/ Show elements inside the div</button>

A: $(*) is used to select all elements inside the document. Refer this: https://www.w3schools.com/jquery/sel_all.asp

A: $(*) is a selector in jqueryto select all elements
and hence
$("*").hide(); will hide all elements

$(document).ready(function(){
    $("button").click(function(){
        $("*").hide();
    });
});

Hello

World

Good Morning
<button>Hide</button>

Docs


text:
Q: New Google Cloud Messaging on Android 2.3 I created an application which use a new library Google Cloud Messaging. Application works fine on newer Android 4.1. But, on android 2.3 don't works, because method register() from GoogleCloudMessaging class don't returns id of device. Do you have any idea how to fix it?
I will be grateful!

A: I fixed it. In manifest file where is "receiver" I added this
<category android:name="com.main.package"/>

Without this, older device doesn't get id


text:
Q: How to call prototype function within prototype function onclick event How can I call prototype function within inside another prototype function onclick event in JavaScript?
function foo(){
    this.table = '';
}

foo.prototype.abc = function(){
    this.table = document.getElementById("tableID");
    if (table != null) {
        for (var i = 0; i < table.rows.length; i++) {
            for (var j = 0; j < table.rows[i].cells.length; j++)
            table.rows[i].cells[j].onclick = function () {
                this.xyz(this);
            };
        }
    }
}

foo.prototype.xyz = function(tableCell){
    alert(tableCell.innerHTML);
}

If I just call this tableText function instead of this.xyz it will work fine, but using this.xyz gives error in console this.xyz(this) is not a function
function tableText(tableCell) {
    alert(tableCell.innerHTML);
}

My browser showing error but not JSFiddle
JS Fiddle

A: In this block of code:
table.rows[i].cells[j].onclick = function () {
    this.xyz(this);
};

this represents the td HTML object, not foo. You have to keep a reference of foo and pass it into onclick function, like this:
foo.prototype.abc = function(){
    var that = this; //Keep a reference of `foo`
    this.table = document.getElementById("tableID");
    if (table != null) {
        for (var i = 0; i < table.rows.length; i++) {
            for (var j = 0; j < table.rows[i].cells.length; j++)
            table.rows[i].cells[j].onclick = function () {
                //this.xyz(this);
                // "that" refer to the function foo
                // "this" refer to the current table cell (td)
                that.xyz(this);
            };
        }
    }
}


text:
Q: Internet stops working when using static IP I am running windows 8.1 and I am trying to configure a static IP address for server hosting. Without using a static IP address, my IPV4 properties are these:

And the internet and web work fine. However, when I try to set up a static IP as so:

My internet does this:

And gives this warning about multiple Default Gateways.
The result of ipconfig/all is:

Microsoft Windows [Version 6.3.9600] (c) 2013 Microsoft Corporation.
  All rights reserved.
C:\Users\Phoenix>ipconfig/all
Windows IP Configuration
Host Name . . . . . . . . . . . . : Caroline    Primary Dns Suffix
  . . . . . . . :    Node Type . . . . . . . . . . . . : Hybrid    IP
  Routing Enabled. . . . . . . . : No    WINS Proxy Enabled. . . . . . .
  . : No
Wireless LAN adapter Local Area Connection* 2:
Media State . . . . . . . . . . . : Media disconnected
  Connection-specific DNS Suffix  . :    Description . . . . . . . . . .
  . : Microsoft Wi-Fi Direct Virtual Adapter    Physical Address. . . .
  . . . . . : AE-22-0B-BE-B0-3C    DHCP Enabled. . . . . . . . . . . :
  Yes    Autoconfiguration Enabled . . . . : Yes
Wireless LAN adapter Wi-Fi:
Connection-specific DNS Suffix  . :    Description . . . . . . . .
  . . . : ASUS PCE-AC68 802.11ac Network Adapter    Physical Address. .
  . . . . . . . : AC-22-0B-BE-B0-3C    DHCP Enabled. . . . . . . . . . .
  : Yes    Autoconfiguration Enabled . . . . : Yes    Link-local IPv6
  Address . . . . . : fe80::9573:d94:99d4:acd9%4(Preferred)    IPv4
  Address. . . . . . . . . . . : 192.168.1.2(Preferred)    Subnet Mask .
  . . . . . . . . . . : 255.255.255.0    Lease Obtained. . . . . . . . .
  . : Thursday, July 21, 2016 1:57:39 PM    Lease Expires . . . . . . .
  . . . : Friday, July 22, 2016 1:57:38 PM    Default Gateway . . . . .
  . . . . : 192.168.1.1    DHCP Server . . . . . . . . . . . :
  192.168.1.1    DHCPv6 IAID . . . . . . . . . . . : 128721419    DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-1C-90-9F-4F-38-2C-4A-B2-B6-3B
DNS Servers . . . . . . . . . . . : 8.8.8.8    NetBIOS over Tcpip.
  . . . . . . . : Enabled
Ethernet adapter Hamachi:
Connection-specific DNS Suffix  . :    Description . . . . . . . .
  . . . : LogMeIn Hamachi Virtual Ethernet Adapter    Physical Address.
  . . . . . . . . : 7A-79-19-14-B7-AB    DHCP Enabled. . . . . . . . . .
  . : Yes    Autoconfiguration Enabled . . . . : Yes    IPv6 Address. .
  . . . . . . . . . : 2620:9b::1914:b7ab(Preferred)    Link-local IPv6
  Address . . . . . : fe80::791b:4133:574d:8ae7%10(Preferred)    IPv4
  Address. . . . . . . . . . . : 25.20.183.171(Preferred)    Subnet Mask
  . . . . . . . . . . . : 255.0.0.0    Lease Obtained. . . . . . . . . .
  : Thursday, July 21, 2016 1:52:25 PM    Lease Expires . . . . . . . .
  . . : Friday, July 21, 2017 1:52:24 PM    Default Gateway . . . . . .
  . . . : 2620:9b::1900:1
                                         25.0.0.1    DHCP Server . . . . . . . . . . . : 25.0.0.1    DHCPv6 IAID . . . . . . . . . . . :
  184701170    DHCPv6 Client DUID. . . . . . . . :
  00-01-00-01-1C-90-9F-4F-38-2C-4A-B2-B6-3B
DNS Servers . . . . . . . . . . . : fec0:0:0:ffff::1%1
                                         fec0:0:0:ffff::2%1
                                         fec0:0:0:ffff::3%1    NetBIOS over Tcpip. . . . . . . . : Enabled
Tunnel adapter isatap.{CFB2AF4B-309A-433C-806C-6E35B6ECC8AF}:
Media State . . . . . . . . . . . : Media disconnected
  Connection-specific DNS Suffix  . :    Description . . . . . . . . . .
  . : Microsoft ISATAP Adapter    Physical Address. . . . . . . . . :
  00-00-00-00-00-00-00-E0    DHCP Enabled. . . . . . . . . . . : No
  Autoconfiguration Enabled . . . . : Yes
Tunnel adapter Teredo Tunneling Pseudo-Interface:
Connection-specific DNS Suffix  . :    Description . . . . . . . .
  . . . : Teredo Tunneling Pseudo-Interface    Physical Address. . . . .
  . . . . : 00-00-00-00-00-00-00-E0    DHCP Enabled. . . . . . . . . . .
  : No    Autoconfiguration Enabled . . . . : Yes    IPv6 Address. . . .
  . . . . . . . : 2001:0:9d38:90d7:43d:3527:3f57:fefd(Prefe rred)
  Link-local IPv6 Address . . . . . :
  fe80::43d:3527:3f57:fefd%7(Preferred)    Default Gateway . . . . . . .
  . . :    DHCPv6 IAID . . . . . . . . . . . : 318767104    DHCPv6
  Client DUID. . . . . . . . : 00-01-00-01-1C-90-9F-4F-38-2C-4A-B2-B6-3B
NetBIOS over Tcpip. . . . . . . . : Disabled
Tunnel adapter isatap.{C61B7E6E-CCE5-4B38-987F-9EF19A3AEA1E}:
Media State . . . . . . . . . . . : Media disconnected
  Connection-specific DNS Suffix  . :    Description . . . . . . . . . .
  . : Microsoft ISATAP Adapter #3    Physical Address. . . . . . . . . :
  00-00-00-00-00-00-00-E0    DHCP Enabled. . . . . . . . . . . : No
  Autoconfiguration Enabled . . . . : Yes

The result of route print is:

The weirdest part of this (to me) is that this was working before, but stopped working when microsoft forcibly installed an update, and has stopped working several times in the past upon microsoft installing an update. Any ideas what's causing this?

A: As posted in the comments, the computer was giving a Default Gateway conflict warning.  This is where the computer is looking to get out to the internet.  The Hamachi network is conflicting with the internal network.  Disable this network then set the static IP.


text:
Q: How much of GCH do we need to guarantee well-ordering of continuum? It's well known that, if GCH holds, then every cardinal can be well-ordered. However, I'm sure we don't need full power of GCH to prove it for specific cardinal, e.g. continuum. I have been wondering, what is the minimum amount cardinal numbers $A$ for which non-existence of cardinal $B$ with $A<B<2^A$ guarantees that $\frak{c}$ can be well ordered (or, simplier, GCH for which cardinals already implies existence of well-ordering of $\frak{c}$)? By looking through the proof I think it's enough for it to hold for $A\in\{\mathbb{R},2^\mathbb{R},2^{2^\mathbb{R}}\}$.
Thanks in advance for help!

A: Yes, you are right. This is a theorem of Specker. If there are no intermediate cardinals between $A,\mathcal P(A)$ and $\mathcal{P(P(}A))$, then $A$ can be well-ordered.
You can find nice details in:

Akihiro Kanamori, David Pincus, "Does GCH imply AC locally?, in "Paul Erdős and his mathematics, II (Budapest, 1999)", Bolyai Soc. Math. Stud., 11, János Bolyai Math. Soc., Budapest, (2002), 413–426.

Link to the paper on Kanamori's website.
And on this relevant thread.

I had discussed this answer with Yair Hayut earlier this evening, and then I noticed the following peculiar thing.
Suppose that $\sf CH$ holds for $\Bbb R$ and $\aleph_1$, then $2^{\aleph_0}=\aleph_1$ or $2^{\aleph_0}=\aleph_2$. In either case, it is well-orderable.

*

*First we observe that since there is a definable surjection from $\Bbb R$ onto $\omega_1$, it is necessarily the case that $\aleph_1$ and $2^{\aleph_1}$ are both $\leq2^{2^{\aleph_0}}$, with $\aleph_1$ being strictly smaller. Therefore $\aleph_1\leq2^{\aleph_0}\leq2^{\aleph_1}\leq2^{2^{\aleph_0}}$, but our assumptions tell us it is impossible that all three are strict inequalities. Either the middle one is equality, or both the left and right ones are equality (but not both, of course).

*If $2^{\aleph_0}<2^{\aleph_1}$, then we have that $\aleph_1\leq2^{\aleph_0}<2^{\aleph_1}$, and therefore $2^{\aleph_0}=\aleph_1$.

*If $2^{\aleph_1}=2^{\aleph_0}$ then $\aleph_2<2^{2^{\aleph_0}}$ (since there is a definable surjection from $2^{\omega_1}$ onto $\omega_2$, so by this assumption there is a surjection from $\Bbb R$ onto $\omega_2$). If $2^{\aleph_0}$ and $\aleph_2$ are incomparable then we get $2^{\aleph_0}<2^{\aleph_0}+\aleph_2<2^{2^{\aleph_0}}$ which is a contradiction (this is the same argument by $\aleph_1\leq2^{\aleph_0}$). Therefore $\aleph_2\leq 2^{\aleph_0}$. If they are equal, wonderful.
Otherwise, $\aleph_1<\aleph_2<2^{\aleph_0}=2^{\aleph_1}$ which is a contradiction to our assumption that $\sf CH(\aleph_1)$ holds.
So while it doesn't decrease the number of sets which required here, it does give a nice twist on the things. I'm not sure if we can get rid of the assumption of $\sf CH(\aleph_1)$, maybe at the cost of requiring $\sf CH(\aleph_2)$, and to remove that assumption we would need to go on and on. I'm not sure what happens at the limit, though.
Therefore, this raises a nice question:

Suppose that $\aleph(\Bbb R)=\aleph^*(\Bbb R)=\aleph_\omega$, does this imply that $\sf CH(\Bbb R)$ fails, or is it consistent that $\sf CH(\Bbb R)$ holds? What if we replace $\omega$ by an arbitrary limit ordinal?


text:
Q: Can I determine which paths RubyGems added to the load path to make my command line app work? In a gemspec, I can specify the require_paths, which represent paths I want to be able to require from at runtime.  These get put into the $LOAD_PATH by RubyGems.
My question is: is there a way I can determine what these paths are at runtime?  Can I examine elements of $LOAD_PATH and know which ones were added just for my gem?
Update: Ultimately, I would like to dynamically load ruby files from inside the gem, e.g.
load_from 'foo/bar'

And have that find $MY_GEMS_LIB_DIR/foo/bar/*.rb.  I can certainly go through the entire $LOAD_PATH looking for foo/bar, but I'd rather restrict it just to the gem.

A: I don't know if I understood your needing (my english is bad :-/ ); anyway, if the problem is to determine the directories that will be loaded when you require a gem you can use Gem::Specification.lib_dirs_glob:
Gem::Specification.find_by_name('irbtools').lib_dirs_glob
#=> "/home/my_user/.rvm/gems/ruby-1.9.3-p125/gems/irbtools-1.2.2/lib"

Gem::Specification.find_by_name('xyz').lib_dirs_glob
# raises a Gem::LoadError

So a possible implementation of load_from could be:
def load_from(gem_name, path)
  path_to_load = File.join(Gem::Specification.find_by_name(gem_name).lib_dirs_glob, path)
  Dir.glob(path_to_load).each(&method(:load))
end

Trying to load Thor::CoreExt :
Thor::CoreExt #=> NameError: uninitialized constant Thor
load_from 'thor', 'thor/core_ext/*.rb'
Thor::CoreExt #=> Thor::CoreExt

This works on my machine with ruby 1.9.3 and gem 1.8.21 .

A: If I understand you correctly, this should do (Ruby 1.9.3):
before = $LOAD_PATH.dup
require 'the_gem'
added_paths = $LOAD_PATH - before

Of course, this will include the paths added by the dependencies.

A: You can use the $: global in irb. There is also the gem which command which gives you a library path, but I'm not sure if that includes exactly what you want.

A: Looks like Gem.find_files may help you.


text:
Q: function to print linked list in reverse order I was searching on how can I print a reverse of linked list and I found this piece of code
/* Function to reverse the linked list */
void printReverse(struct node* head)
{
    // Base case
    if (head == NULL)
       return;

    // print the list after head node
    printReverse(head->next);

    // After everything else is printed, print head
    printf("%d  ", head->data);
}

The problem is that I do not understand the part where it reaches the last pointer which points to NULL and how it comes back one by one and prints the linked list in reverse order.
Is the return statement what makes it go step by step back? Or something else? Please help because I do not understand.

A: This is a recursive function. Recursive functions work by pushing variables onto the execution stack. The execution order pops off the stack in reverse order from the order it was pushed on the stack. This means that the last execution prints first, then the one previous to that, and so forth until all executions of printReverse print their values.

A: This is a recursive function; that is to say, it calls itself.
Let's use the sequence example as your example data:
When you first run the function, it's pointing at the head, and the head is the item containing the data e. It has a next property, which is the item containing the data x. Therefore, head == NULL evaluates False and the if statement doesn't fire.
The function then calls a second copy of itself, pointing to the next item in the list - the item containing x. This has a next property, which is the item containing a. The function then calls a third copy of itself with this item, and so on and so forth until it hits the final e, and calls a copy of itself with the next property of that item - that is to say, it calls itself with NULL as the input.
This copy of the function then returns due to the if statement- crucially, it returns to the function that called it, in this case the copy of itself the level above. This copy then carries on where it left off, executing printf("%d  ", head->data); - in this case, it prints an e. Then it falls out of the body of the function and so returns to the function that called it. This copy of the function will have a head->data value of l, and this will print as above. As such, it then runs through back up the chain until it gets to the original function call, prints the first e, and then returns to the function that called it.
Hope this makes sense, I know it's not the best or most elegant explanation of recursion but there's a lot of material out there if this is confusing explaining exactly how recursion works and how useful it can be!

A: The thing that makes it go in reverse is to have the printf() call after the recursive call to itself.
You can try interchanging the two calls as in
void printNormal(struct node* head)
{
    // Base case
    if (head == NULL)
       return;

    // Before all, we print this node info.
    printf("%d  ", head->data);

    // print the rest of the list after this node
    printReverse(head->next);

}

And you'll get the forward printing of the list.
The mission of the so commented Base case is to avoid infinite recursion.  The end of the list is special, we can do the check on entering the printReverse() function, so we can deal with the special case of an empty list, or we have to do it at each call (then we should put a check before calling the function inside it, and in the code that calls the recursive function (better to put it at the beginning).

A: As others have already explained the recursive version. I suggest you to have a look at this iterative version of printing linked list in reverse order. This is more easy to understand and implement as compared to recursive version, however it increases time complexity.
    // To ease testing of code here linked list is created randomly of given size.
    #include<stdio.h>
    #include<cstdlib>
    #include<time.h>
    #define size 10 //Size of list
    struct node
    {
          int info;
          struct node * next;
    };
    typedef struct node* Node;
    Node start;
    int main()
    {
       int i;
       srand(time(NULL));
       for(i=0;i<size;i++)
       {
          Node ptr;
          ptr=(Node)malloc(sizeof(node));
          ptr->info=rand()%100; //random list is created of given size.
          ptr->next=NULL;
          if(start==NULL)
              start=ptr;
          else
          {
               ptr->next=start;
               start=ptr;
          }
    }
    printf(" Traversal of Linked List in forward direction -\n");
    Node temp=start;
    while(temp!=NULL)
    {
        printf(" %d ",temp->info);
        temp=temp->next;
    }
    printf("\n Traversal of Linked List in backward direction -\n");
    Node ptr=NULL;
    while(ptr!=start)
    {
        temp=start;
        while(temp->next!=ptr)
        temp=temp->next;
        printf(" %d ",temp->info);
        ptr=temp;
    }
       return 0;
    }

For more details visit-
https://github.com/SahdevKansal02/Data-Structures-And-Algorithms.git

A: Jim Rodgers hits the nail on the head. However, you could make life very easy for yourself by having a doubly linked list.
So for example your entry (node) has both a previous and next member pointing to the previous entry and next entry respectively. Then you don't need more "obfuscated" code than necessary.


text:
Q: ModelState is not valid due to validation on a nullable number I have in Model the property called "ID" of type "int?". And in View
@Html.HiddenFor(m => m.ID)

If Model.ID is null, the hidden field will have the value an empty string and on postback, ModelState.IsValid returns false because of the error:
"Object of type 'System.String' cannot be converted to type 'System.Nullable`1[System.Int32]'."

What exactly am I doing wrong?

A: Try the below in your view:
var id = Model.ID.HasValue ? Model.ID.Value : false;
@Html.HiddenFor(m=> id)

A: The issue here is that MVC apparently uses the same template for Html.HiddenFor() for a nullable int (int?) value as it does for a normal int. One pretty simple solution would be to only emit the hidden field in cases where the value is non-null:
@if ( Model.NullableInt.HasValue ) {
    @Html.HiddenFor(m => m.NullableInt);
}

In the case where Model.NullableInt is null, the hidden field won't be emitted, and thus you won't have the problem of an empty string showing up when you try to validate.

A: Well, this in not the common behavior, I was extending in the project the DefaultModelBinder such that null values are being converted to empty strings and that's what was causing the error.

A: We do this every day in our solution and it's not an issue at all. Here is one of our models just as an example:
public class ClassifiedAd : BaseModel
{
    [Key]
    [Editable(false)]
    public int? ClassifiedAdID { get; set; }

    [Required(ErrorMessage = "Required!")]
    public int? UserID { get; set; }

    [Required(ErrorMessage = "Required!")]
    public int? ClassifiedAdCategoryID { get; set; }

    [Required(ErrorMessage = "Required!")]
    [StringLength(15, ErrorMessage = "Limited to 15 characters!")]
    [RegularExpression(RegularExpressions.USPhone, ErrorMessage = "Must be a valid phone number!")]
    public string Phone { get; set; }

    [Required(ErrorMessage = "Required!")]
    [RegularExpression(RegularExpressions.SafeAlphaNumeric, ErrorMessage = "Only letters, numbers, dashes and underscores are allowed!")]
    [StringLength(100, ErrorMessage = "Limited to 100 characters!")]
    public string AddTitle { get; set; }
}

as you can see we use nullable types for all our model properties. This however does not cause any issues that you describe. In our views we have:
@Html.HiddenFor(model => model.ClassifiedAdID)
@Html.HiddenFor(model => model.UserID)

and everything maps and works fine. I'm not sure what causes your problem (need to see your entire code to figure that out) but I think you need to look at other possibilities here. What version of MVC are you using?


text:
Q: Issue finding $F$ (distribution function) given $f$ (density function) $X$ is a random variable with density function
$$f(x) = \begin{cases}
c(1-x^2) &\mbox{if }-1 < x < 1 \\
0 &\mbox{otherwise}
\end{cases}$$
The problem statement requires us to find $c$ and consequently find $F$. I found $c = \frac{3}{2}$ by setting up the integral $\int_{0}^{1}c(1-x^2)dx = 1$ and solving for $c$.
My issue starts when trying to find the distribution function $F$.
I used the definition in my textbook: $F_X(t) = \int_{-\infty}^{t}f_X(x)dx$.
Because of the piecewise nature of $f$, we would have 2 cases:
$t\leq -1$: $\int_{-\infty}^{t}0dx = 0$
$t > -1$: This is the case that confuses me. I compute the integral $\int_{-\infty}^{t} \frac{3}{2}(1-x^2)dx$ and get $-\infty$. This doesn't seem right to me. Where did I go wrong?
EDIT: I suspect that I should actually set up the second integral as $\int_{-1}^{t} \frac{3}{2}(1-x^2)dx$ instead.

A: Yes, your suspicion is correct. The density function $f_X(x)$ is equal to $0$ if $x\not\in(-1,1)$. Hence,
$$
F_X(t)=\int_{-\infty}^tf_X(x)\mathrm dx=\int_{-\infty}^{-1}f_X(x)\mathrm dx+\int_{-1}^tf_X(x)\mathrm dx=\int_{-1}^tf_X(x)\mathrm dx=c\int_{-1}^t1-x^2\mathrm dx
$$
for $-1\le t\le1$.


text:
Q: How to check CSRF token using AJAX and CakePHP 3 when user is not logged in? So I made my site live and I am entering into the public realm where people aren't always nice. I just started learning about CSRF and saw that it was something I needed when I made my cakephp 3 site live. As seen here!
I added the csrf component and the security component to my site, but I have 1 major problem. Now, when users want to sign up they can't. I use a custom form for stripe to send payment, but also add a user using ajax to my database. The user gets added first and then the payment is processed and saves the order to the database as well.
According to stripe docs I add the token in a hidden value to the form after I click the submit button and can't help but notice that my new security is not allowing this to happen.
Since I am using ajax to send the post data to my users controller and adding a form input on submit,
How do I check the csrf token and make sure there isn't a security leak without disabling the security for the actions involved?
An example of how this is to be done would be greatly appreciated since examples seem to be lacking for doing this in cakephp 3. It is also hard for me to figure out how everything works since the cakephp 3 automagic adds the tokens to the forms and cookie. I am unsure how/where/what to check.

A: For pass X-CSRF-Token, use beforeSend parameter in your Ajax request, and define csrfToken value of cookie.
$.ajax({
    url: '/foo/bar',
    type: 'POST',
    dataType: 'HTML',
    data: data,
    beforeSend: function(xhr){
        xhr.setRequestHeader('X-CSRF-Token', csrfToken);
    },
})
.done(function(data) {
    alert('done !');
});

A:
According to stripe docs I add the token in a hidden value to the form after I click the submit button and can't help but notice that my new security is not allowing this to happen.

Cake's CSRF token would have no effect when POSTing to another site.

Since I am using ajax to send the post data to my users controller and adding a form input on submit,
How do I check the csrf token and make sure there isn't a security leak without disabling the security for the actions involved?

The CSRF token is available in cookie named csrfToken, so read that token in your javascript and set X-CSRF-Token header for your AJAX request. The CsrfCompoment will do the checking.

A: using js function:

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}
...
then
$.ajax
        ({
            type: "Post",
            url: "URL_HERE",
            data: {some_data},
            beforeSend: function(xhr){
                xhr.setRequestHeader('X-CSRF-Token', getCookie('csrfToken'));
            },
            success: function (e) {
            },
            errors: function () {
            }
        });


text:
Q: Can Controller fully replace what http handler does? I want to know if controller can fully replace http handler when no view involved. The function looks similar.

A: Sure:
public ActionResult Index()
{
    return Content("No view involved here", "text/plain");
}

or:
public ActionResult Index()
{
    return File("test.pdf", "application/pdf");
}

or:
public ActionResult Index()
{
    return Json(new { foo = "bar" });
}

In all those examples, there's no view involved. The controller acts as an HTTP handler.


text:
Q: Configure Gitlab to run on different port So I tried many different ways of doing this but I can't seem to get it to work. I have the latest gitlab downloaded on CentOS 7. I changed the external_url on etc/gitlab'gitlab.rb to http://domain.com:987. No luck.
Then I changed the nginx setting listen_port to 987 and still no luck. But port 80 seem to be working fine. I am not sure what I am doing wrong. Can someone please help?


text:
Q: Laravel collection get min by key I'm trying to find a way to get the minimum amount of a collection and return it with the id as well. Pretty sure there is a quick way around it but could not find a solution yet.
$collection = collect();
$collection->push(['id' => 3, 'count' => 24]);
$collection->push(['id' => 43, 'count' => 14]);
$collection->push(['id' => 11, 'count' => 84]);

dd($collection->min('count'));

When I do that, it only returns the "count" value. I need to retrieve the minimum count with the id it belongs to.

A: The min() method only returns the value for the given key, not the whole row. Thankfully, the sortBy() method is available, and combined with ->first(), should get you what you need:
$collection = collect();
$collection->push(['id' => 3, 'count' => 24]);
$collection->push(['id' => 43, 'count' => 14]);
$collection->push(['id' => 11, 'count' => 84]);

$minRecord = $collection->sortBy('count')->first();
dd($minRecord); // ["id" => 43, "count" => 14]

References:
https://laravel.com/docs/8.x/collections#method-sortby
https://laravel.com/docs/8.x/collections#method-first


text:
Q: Typesetting a style of bibliography used a lot in mathematics literature In mathematics books and articles people tend to use the following formation for their citations:
while In the body of the article you see something like this: "According to [B] and [Be] blah blah blah." I want to typeset this style for my own works.
I did a search and although I'm not sure but I think this style is called alphanum? The problem is I could not run my code with alphnum style: Here is my code for the style alpha (which works)
\documentclass[11pt]{book}

\begin{document}
Trial \cite{Hu} and \cite{knapp}.

\bibliographystyle{alpha}
\bibliography{foo}

\end{document}

This runs perfectly but the moment I replace the style with alphanum, although the code still compiles, the bibliography becomes non-existent and cites become replaced with [?]. Clearly my compiler doesn't recognize this style. So I have no way of checking whether the style I want is in fact alphanum. So my question is two-fold:

Is this style alphanum and if not what is it? Whatever it is how can I use it?

Oh and I almost forgot to mention: I use Windows and MikTeX.

A: Here is an example of doing this with biblatex. The important parts are the \DeclareLabelalphaTemplate and the \DeclareFieldFormat. The former sets the label format and the latter ensures that the extraalpha field remains numeric. Note that this is not exactly like your example output simply because of the order of the references but this should not matter as what you need is unique labels of a particular format.
\documentclass{article}
\usepackage[style=alphabetic]{biblatex}
\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}

@BOOK{test1,
  AUTHOR = {Bourbaki, N.},
  Title  = {Title}
}
@BOOK{test2,
  AUTHOR = {Bernard, D.},
  Title  = {Title}
}
@BOOK{test3,
  AUTHOR = {Bernard, D. and Felder, G.},
  Title  = {Title}
}
@BOOK{test4,
  AUTHOR = {Cherednik, I.},
  Title  = {Title1}
}
@BOOK{test5,
  AUTHOR = {Cherednik, I.},
  Title  = {Title2}
}
@BOOK{test6,
  AUTHOR = {Cherednik, I.},
  Title  = {Title3}
}
\end{filecontents}
\addbibresource{\jobname.bib}
\DeclareLabelalphaTemplate{
  \labelelement{
    \field[varwidthlist]{labelname}
  }
}
\DeclareFieldFormat{extraalpha}{#1}%
\begin{document}
\nocite{*}
\printbibliography
\end{document}


text:
Q: java - dynamic casting using strings Consider a sqlite database table DRINK with columns: Name(String), Description(String), ResourceID(int).
Now, after I get a Cursor cur everytime I'd like to get something out of a particular row, I'd have to do something like:
cur = db.query(...);
String name = cur.getString(0);
String desc = cur.getString(1);
int desc = cur.getInt(0);

But, this logic is so dependent on my knowledge of knowing the database table schema and I'd like to avoig that. What I'd like to do is something like this:
Object x = cur.getObject(0); //not available

but, as marked the getObject is not available to a cursor
but, I also require while doing this the data types are also preserved, meaning, a 1 stored as integer in its ResourceID column, does not give 1 instanceOf String=true, it should give 1 instanceOf int=true.
so, why would I want to do that? If I can do this, then I can obtain values from the database in something like a for loop without having the worry what is in the schema and providing only it's length.
What are the ways this can be achieved, or atleast achieving a similar behaviour.

A: Call getType() then use a switch statement to call the appropriate getXxx() method.


text:
Q: can anyone help me to solve the error::: Parse error: syntax error, unexpected T_FUNCTION in /localhost/braintree/app.php on line 14 <?php

require_once 'braintree-php-2.14.0/lib/Braintree.php';
require_once __DIR__ . 'silex/vendor/autoload.php';
Braintree_Configuration::environment('sandbox');
Braintree_Configuration::merchantId('...');
Braintree_Configuration::publicKey('...');
Braintree_Configuration::privateKey('...');
$app = new Silex\Application();
$app->get('/', function () {
    include 'views/form.php';
});
$app->run();
//$app->get("/braintree-php-2.14.0", function () {
$app->get("/braintree", function () {
   include 'views/response.php';
});
?>

this is braintree payments system i read the documentation clearly but not solved.error is found in this line 14:   $app->get("/braintree", function () {

A: It looks like the problem is that anonymous functions are only available in PHP 5.3+. If at all possible I'd suggest upgrading your server to the newest version of PHP available, 5.4.7.
Another issue might be that you're calling $app->run() before you add the response hook, so I'd move the run() call to the end.
If you can't upgrade PHP then the following fix should work:
<?php
require_once 'braintree-php-2.14.0/lib/Braintree.php';
require_once __DIR__ . 'silex/vendor/autoload.php';
Braintree_Configuration::environment('sandbox');
Braintree_Configuration::merchantId('...');
Braintree_Configuration::publicKey('...');
Braintree_Configuration::privateKey('...');
$app = new Silex\Application();
function form() {
  include 'views/form.php';
}
$app->get('/', form);
function response() {
  include 'views/response.php';
}
$app->get("/braintree", response);
$app->run();
?>

The other reason I really like PHP 5.4 is that it includes a lightweight (ie not for production) server that makes testing and debugging a lot easier. I'm a Braintree dev and wrote the guide this came from so I hope this helps!


text:
Q: Like with argument "_" not working I am using the following command with SQL Server 2008 R2 to display companies name(c_name) whose second alphabet is 'e'. I am not getting any results.
select c_name from ind_comp where c_name LIKE '_e'

EXPECTED Results:
 Rows 1, 4,7,10

ACTUAL:
    No rows returned
Sample Table rows (table: ind_comp):
Sno c_name          addrs               turnover
1   pesodent        B-12/7 Kolkata      250
2   Colgate         127 Mumbai          519
3   Prestiege       56H Jharkhand       120
4   Relexo          D-45/12 New Delhi   358
5   Bajaj           450, Channai        840
6   TATA            C/90 Bihar          508
7   Reliance        Y-90 New Delhi      700
8   ShaktiBhog      A 120 Punjab        950
9   Kotak Mahindra  B-12 Mumbai         950
10  Pepsi India     5/40 Haryana        600
11  Air India       WZ-90 Goa           1000

A: Your query will only return entries that are 2 characters long that end with an e. You need to use the % wildcard to include entries of any length greater than 2 characters.
SELECT c_name FROM ind_comp WHERE c_name LIKE '_e%'

A: try using
select c_name from ind_comp where c_name LIKE '_e%'


text:
Q: Find word into cell Excel - VBA
I was wondering how to find a word into a Excel range of rows using VBA. Ex. "word to be found", this is not just the cell value but a word into a string. For instance, the way to find the word "network" into the string "Need help to map network printer".
Sub SearchForSfb()

   Dim LSearchRow As Integer
   Dim LCopyToRow As Integer

   On Error GoTo Err_Execute

   'Start search in row 1
   LSearchRow = 1

   'Start copying data to row 2 in Open (row counter variable)
   LCopyToRow = 2

   While Len(Range("E" & CStr(LSearchRow)).Value) > 0

      'If value in column E = "word to be found", copy entire row to Open
      If Range("E" & CStr(LSearchRow)).Value = "word to be found" Then

         'Select row in Data to copy
         Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
         Selection.Copy

         'Paste row into SFB in next row
         Sheets("SFB").Select
         Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
         Sheets("SFB").Paste

         'Move counter to next row
         LCopyToRow = LCopyToRow + 1

         'Go back to Data to continue searching
         Sheets("Data").Select

      End If

      LSearchRow = LSearchRow + 1

   Wend

   'Position on cell A3
   Application.CutCopyMode = False
   Range("A3").Select

   MsgBox "All matching data has been copied."

   Exit Sub

Err_Execute:
   MsgBox "An error occurred."

End Sub

A: Use a simple loop
Sub Button1_Click()
    Dim ws As Worksheet
    Dim sh As Worksheet
    Dim lstRw As Long
    Dim rng As Range
    Dim s As String
    Dim c As Range

    s = "* network *"

    Set ws = Sheets("Data")
    Set sh = Sheets("SFB")

    With ws
        lstRw = .Cells(.Rows.Count, "E").End(xlUp).Row
        Set rng = .Range("E2:E" & lstRw)
    End With

    For Each c In rng.Cells
        If c.Value Like s Then
            c.EntireRow.Copy sh.Cells(sh.Rows.Count, "A").End(xlUp).Offset(1)
        End If
    Next c

End Sub

Or you can use a filter macro
Sub FiltExample()
    Dim ws As Worksheet, sh As Worksheet
    Dim rws As Long, rng As Range
    Set ws = Sheets("Data")
    Set sh = Sheets("SFB")

    Application.ScreenUpdating = 0

    With ws
        rws = .Cells(.Rows.Count, "E").End(xlUp).Row
        .Range("E:E").AutoFilter Field:=1, Criteria1:="=*network*"
        Set rng = .Range("A2:Z" & rws).SpecialCells(xlCellTypeVisible)
        rng.EntireRow.Copy sh.Cells(sh.Rows.Count, "A").End(xlUp).Offset(1)
        .AutoFilterMode = False
    End With

End Sub


text:
Q: Cypher, how do I use MATCH on a result without messing up the original result I'm gonna try to make as much sense as possible, It's also very likely that what I've written is not a good approach to what I want to do, in which case I'd appreciate some pointers in the right direction.
What I want to do is create a node:Hang and create relations to each of the nodes:User that are in a defined array, after that, MATCH one of the created relations based on the fb_id on one of its nodes. SET a property on that relationship and RETURN the first nodes:User i matched.
What I have below does all that I want, with the exception of that it returns the user with the matched relation and not my originally matched users.
How do I make it so it returns the original matched users? (xxxx, zzzz)
 CREATE (hang:Hang {})
 WITH hang
 MATCH (users:User) WHERE users.fb_id IN [xxxx, zzzz]
 CREATE (users)-[:member {status: 0}]->(hang)
 WITH users, hang
 MATCH (users)-[r:member]->(hang) WHERE users.fb_id = xxxx
 SET r.founder = 1, r.status = 1
 RETURN users

A: I think you make sense. I made an example. Here are three users:
CREATE (:User {fb_id:1234}),
       (:User {fb_id:5678}),
       (:User {fb_id:9101});

Then, if you want to create a [member] relationship from Users 1234 and 5678 to Hang, but only set founder=1 and status=1 for User 1234 while still returning both users:
CREATE (hang:Hang {name:'Some Hang'})
WITH hang
MATCH (users:User) WHERE users.fb_id IN [1234, 5678]
CREATE (users)-[r:member]->(hang)
SET r.founder = CASE WHEN users.fb_id = 1234 THEN 1 ELSE 0 END,
    r.status = CASE WHEN users.fb_id = 1234 THEN 1 ELSE 0 END
RETURN users;

This returns both Users 1234 and 5678 in the end, but only sets founder=1 and status=1 on the [member] relationship between User 1234 and Hang.


text:
Q: Create GLSurfaceView from OpenGL ES texture I need to implement a video call feature in a QT app for Android. I've found that it's a pretty complicated and time consuming task to do using QT, as there are no such modules that allow to do that easily. On the other hand, there are plenty of Android libraries and frameworks, that already do it.
So my choice right now is to integrate an android library into my QT project.
The library uses GLSurfaceView to show video call:
GLSurfaceView videoView = (GLSurfaceView) findViewById(R.id.glview_call);

I know that GLSurfaceView must be using OpenGL ES texture under the hood.
I would like to understand how to create GLSurfaceView from a raw texture (glGenTextures), so that the Android library could render into it, and I'll be controlling on QT side where to place this texture on the screen.
Do you know any ways to achieve this?

A: I feel like TextureView with its setSurfaceTexture(SurfaceTexture surfaceTexture) method is the way to go. SurfaceTexture accepts texture id in its constructor. Though it will take some time to check if it really works.


text:
Q: How to understand and use a "program API"? I got sent a link to what is allegedly a "program API" for sort of a marketplace website. It lists some of the ads on the website and I'm supposed to use it as input for a Java app running on the local machine. Example:
    [ {
      "id" : 32376,
      "name" : "Example offer",
      "story" : "Blah blah blah",
      "purpose" : "9",
      "photos" : [ {
        "name" : "neatPicOfTheStuff.jpg",
        "url" : "/loans/32376/photos/2032"
      } ],
      "nickName" : "Pajunda",
      "termInMonths" : 84,
      "interestRate" : 0.049900,
      "rating" : "AAAA",
      "topped" : null,
      "amount" : 215000.00,
      "remainingInvestment" : 123800.00,
      "investmentRate" : 0.4241860465116279,
      "covered" : false,
      "datePublished" : "2016-05-23T09:34:52.323+02:00",
      "published" : true,
      "deadline" : "2016-05-30T08:57:58.050+02:00",
      "investmentsCount" : 149,
      "questionsCount" : 4,
      "region" : "2",
      "mainIncomeType" : "EMPLOYMENT"
    }, {
//another ad
} ]

This data format looks understandable enough, and I probably could cobble together some String processing methods to get what I need out of it, but this looks to me like a standard format of some sort, so I figured out I'd rather ask first rather than spend a day or two reinventing the wheel and making the resulting app hard to maintain to boot. Searching for "program API" returns irrelevant results, and there is no indication of the name of this format. And so I need to know:

*

*If this data is indeed formatted according to some standard, what is its name?

*Is there a library out there to work with it, for iterating through the elements of the list of the ads, extracting values of the variables, and so on?

A: The data format is called JSON and you can read more about it here:
http://www.json.org/
On how to parse JSON in Java you can see this previous answer on StackOwerflow:
How to parse JSON in Java

A: The data you've posted is in JSON Format. There are plenty of libraries like Jackson which you could use to parse JSON content directly into POJOs, etc.


text:
Q: Recursively search directory of binary files for hexadecimal sequence? The current commands I'm using to search some hex values (say 0A 8b 02) involve:
find . -type f -not -name "*.png" -exec xxd -p {} \; | grep "0a8b02" || xargs -0 -P 4
Is it possible to improve this given the following goals:

*

*search files recursively

*display the offset and filename

*exclude certain files with certain extensions (above example will not search .png files)

*speed: search needs to handle 200,000 files (around 50KB to 1MB) in a directly totaling ~2GB.

I'm not too confident if the xargs is working properly for 4 processors. Also I'm having difficulties printing the filename when grep finds a match since it is piped from xxd. Any suggestions?

A: IF:

*

*you have GNU grep

*AND the hex bytes you search for NEVER contain newlines (0xa)[1]

*

*If they contain NUL (0x), you must provide the grep search string via a file (-f) rather than by direct argument.

the following command would get you there, using the example of searching for 0e 8b 02:
LC_ALL=C find . -type f -not -name "*.png" -exec grep -FHoab $'\x{0e}\x{8b}\x{02}' {} + |
  LC_ALL=C cut -d: -f1-2

The grep command produces output lines as follows:
<filename>:<byte-offset>:<matched-bytes>

which LC_ALL=C cut -d: -f1-2 then reduces to <filename>:<byte-offset>
The command almost works with BSD grep, except that the byte offset reported is invariably the start of the line that the pattern was matched on.
In other words: the byte offset will only be correct if no newlines precede a match in the file.
Also, BSD grep doesn't support specifying NUL (0x0) bytes as part of the search string, not even when provided via a file with -f.

*

*Note that there'll be no parallel processing, but only a few grep invocations, based on using find's -exec ... +, which, like xargs, passes as many filenames as will fit on a command line to grep at once.

*By letting grep search for the byte sequence directly, there is no need for xxd:

*

*The sequence is specified as an ANSI C-quoted string, which means that the escape sequences are expanded to literals by the shell, enabling Grep to then search for the resulting string as a literal (via -F), which is faster.
The linked article is from the bash manual, but they work in zsh (and ksh) too.

*

*A GNU Grep alternative is to use -P (support for PRCEs, Perl-compatible regular expressions) with non-pre-expanded escape sequences, but this will be slower: grep -PHoab '\x{0e}\x{8b}\x{02}'

*LC_ALL=C ensures that grep treats each byte as its own character without applying any encoding rules.

*-F treats the search strings as a literal (rather than a regex)

*-H prepends the relevant input filename to each output line; note that Grep does this implicitly when given more than 1 filename argument

*-o only report matched strings (byte sequences), not the whole line (the concept of a line has no meaning in binary files anyway)[2]

*-a treats binary files as if they were text files (without this, Grep would only print text Binary file <filename> matches for binary input files with matches)

*-b reports the byte offsets of matches

If it's sufficient to find at most 1 match in a given input file, add -m 1.

[1] Newlines cannot be used, because Grep invariably treats newlines in a search-pattern string as separating multiple search patterns. Also, Grep is line-based, so you can't match across lines; GNU Grep's -null-data option to split the input by NUL bytes could help, but only if your search byte sequence doesn't also comprise NUL bytes; you'd also have to represent your byte values as escape sequences in a regex combined with -P - because you'll need to use escape sequence \n in lieu of actual newlines.
[2] -o is needed to make -b report the byte offset of the match as opposed to that of the beginning of the line (as stated, BSD Grep always does the latter, unfortunately); additionally, it is beneficial to only report the matches themselves here, as an attempt to print the entire line would result in unpredictably long output lines, given that there's no concept of lines in binary files; either way, however, outputting bytes from a binary file may cause strange rendering behavior in the terminal.


text:
Q: exception during spring time change(DST) in where clause I have a table which has column with data type as "TIMESTAMP(6) WITH LOCAL TIME ZONE"
Problem:
For the below query I get exception which says time zones does not exists.
select * from table where update_time <= CURRENT_TIMESTAMP-3/24;

Exception occurs during one hour window of  spring time change. How do I overcome this?

A: I can't reproduce on my environment, but I think the error is caused by the casting of a DATE datatype to an invalid TIMESTAMP WITH LOCAL TIME ZONE.
For instance in the Europe/Paris time zone, the timestamp 2014-03-30 02:30:00 is invalid:
SQL> SELECT to_timestamp_tz('2014-03-30 02:30 Europe/Paris',
  2                         'yyyy-mm-dd hh24:mi TZR')
  3    FROM dual;
SELECT to_timestamp_tz('2014-03-30 02:30 Europe/Paris',
                       *
ERROR at line 1:
ORA-01878: specified field not found in datetime or interval

This time and day does not exist since the clocks are forwarded between 02:00 and 03:00.
Since your right hand side of the <= operator is a date (adding a timestamp and a number produces a date) and you compare it to a TIMESTAMP WITH LOCAL TIME ZONE, it gets casted to the datatype of the column.
I think using interval arithmetics will solve the issue since this will be converted to a valid timestamp. As an added benefit, the resulting code will be easier to read.
Can you try:
select * from table where update_time <= CURRENT_TIMESTAMP - INTERVAL '3' HOUR;


text:
Q: Nrrd to Nifti file conversion I am looking to convert ~1000 .nrrd files into Nifit (.nii.gz) format. I've been using 3DSlicer's ResampleScalarVectorDWIVolume command-line module to accomplish this task. But this process is really slow. It takes ~4 minutes to convert each file on my system.
I was wondering what tool do people use for such conversions?

A: import vtk

def readnrrd(filename):
    """Read image in nrrd format."""
    reader = vtk.vtkNrrdReader()
    reader.SetFileName(filename)
    reader.Update()
    info = reader.GetInformation()
    return reader.GetOutput(), info

def writenifti(image,filename, info):
    """Write nifti file."""
    writer = vtk.vtkNIFTIImageWriter()
    writer.SetInputData(image)
    writer.SetFileName(filename)
    writer.SetInformation(info)
    writer.Write()

m, info = readnrrd('/media/neubias/b0c7dd3a-8b12-435e-8303-2c331d05b365/DATA/Henry_data/mri.nrrd')
writenifti(m, '/media/neubias/b0c7dd3a-8b12-435e-8303-2c331d05b365/DATA/Henry_data/mri_prueba2.nii', info)

A: The following code can be used for converting all the '.nrrd' files in a folder into compressed 'nifti' format:
import os
from glob import glob
import nrrd #pip install pynrrd, if pynrrd is not already installed
import nibabel as nib #pip install nibabel, if nibabel is not already installed
import numpy as np

baseDir = os.path.normpath('path/to/file')
files = glob(baseDir+'/*.nrrd')

for file in files:
#load nrrd
  _nrrd = nrrd.read(file)
  data = _nrrd[0]
  header = _nrrd[1]

#save nifti
  img = nib.Nifti1Image(data, np.eye(4))
  nib.save(img,os.path.join(baseDir, file[-8:-5] + '.nii.gz'))

For example, this script would convert abc.nrrd and xyz.nrrd files in the baseDir to abc.nii.gz and xyz.nii.gz respectively.


text:
Q: APDU Write block commands on mifare card I have been trying to writing some data to my mifare classic cards. first I send these two commands which returns 90 00:
Load Mifare Keys:
FF 82 20 01 06 FF FF FF FF FF FF
Authenticate:
FF 86 00 03 05 01 00 05 60 00
now I'm  write commands to sector 0 and block 3 and block 4 by this commands
APDU_WRITE_data_1 : FF D  00 03 16
APDU_WRITE_data_1 : FF D  00 04 16
      // writedata1 in block 3 ...
//
    if (nres == SM_SUCCESS)// &&
    //bAPDURes )
{
    nlenrcv = sizeof(btRcv);
    nlencmd = 0;

btCmd[nlencmd++] = 0xFF;                // CLA
btCmd[nlencmd++] = 0xD6;                // INS
btCmd[nlencmd++] = 0x00;                // P1, Mifare Block Number MSB
btCmd[nlencmd++] = 0x03;                // P2, Mifare Block Number LSB
btCmd[nlencmd++] = 16;              // Lc, Data Length
memcpy(btCmd + nlencmd, btWrite_1, 16);
nlencmd += 16;

nres = m_Smart.RFTransmit(DEV_INTERNALRF, nlencmd, btCmd, (DWORD*)&nlenrcv, btRcv_1);

// writedata2 in block 4 ...

if (nres == SM_SUCCESS)// &&
    //bAPDURes )
{
    nlenrcv = sizeof(btRcv);
    nlencmd = 0;

    btCmd[nlencmd++] = 0xFF;                // CLA
    btCmd[nlencmd++] = 0xD6;                // INS
    btCmd[nlencmd++] = 0x00;                // P1, Mifare Block Number MSB
    btCmd[nlencmd++] = 0x04;                // P2, Mifare Block Number LSB
    btCmd[nlencmd++] = 16;              // Lc, Data Length
    memcpy(btCmd + nlencmd, btWrite_2, 16);
    nlencmd += 16;

    nres = m_Smart.RFTransmit(DEV_INTERNALRF, nlencmd, btCmd, (DWORD*)&nlenrcv, btRcv_2);

But it doesn't work
is it the APDU for writing wrong?


text:
Q: Why is this struct initialized with data already in a field? I'm using a library written in C, with my own program that's in C++. They typedef a struct like this:
typedef struct tagCtxt
{
    char     iadl1[50+1];
    char     iadl2[50+1];
    char     iprurb[28+1];
    char     iadl3[50+1];
} PARM;

In one of my methods, I construct it and immediately print the value of one of the fields:
PARM parm1;
cout << "'" << parm1.iadl3 << "'" << endl;

As expected, it's blank/empty:
''

Now I do this, creating parm2:
PARM parm1, parm2;
cout << "'" << parm1.iadl3 << "'\t'" << parm2.iadl3 << "'" endl;

Then I get this:
''    'x��'

The output of the second one varies. Sometimes it looks like XŰ or 8ư or �ǰ or ǰ, etc.
This line appears to fix the symptoms:
memset(&parm2.iadl3, 0, sizeof(parm2.iadl3));

But what is the problem? Why is the char array non-empty for the second one, but not for the first?
Remember, my program is compiled as C++ but the header file I'm using that defines the type is in C. Does that make a difference? I'm including the header file like so:
extern "C"
{
    #include "parm.h"
}

A: This is undefined behavior, the initial value of an automatic variable is indeterminate, you need to initialize variables before you use them.
The C99 draft standard in section 6.2.4 Storage durations of objects says after covering static variables says (emphasis mine):

For such an object that does not have a variable length array type, its lifetime extends
  from entry into the block with which it is associated until execution of that block ends in
  any way. [...] The initial value of the object is indeterminate. [...]

and the definition of indeterminate value is as follows:

either an unspecified value or a trap representation

The C++ draft standard section 8.5 Initializers paragraph 12 says (emphasis mine):

If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value. [ Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2. —end note ]

A good place to get started in understanding some forms of undefined behavior is the Deep C slides.

A: "As expected, it's blank/empty:" No, thats not expected. C++ dones not initialize the value of a  variable (Except its data type provides a constructor which does the job, or is a thing with static storage duration).
As Shafik said, reading the uninitialized data has undefined behaviour.

A: Doesn't matter with the C/C++ thing.
In general, memory which you havn't set explicitly (like that memset operation u did) contains undefined values.
It's not 'expected' to be 0's.

A: C and C++ provides no guarantee regarding values of local variables. They have a garbage values, depending on what is at that memory adress in the moment of allocation. In order to use them, you must initialize them with a value.
This is not true for global variables. They are initialized with 0 by default.

A: char     iadl1[50+1];

Will reserve you a block of memory that are large enough to store 51 characters
However, it doesn't guarantee you that that block of memory is all empty, it just happens to be empty in your case. In general, use memset to initialize your arrays before accessing it would be the best way to do.
memset( iadl1, '\0', sizeof(char)*51);

A: Only static variables have values pre-initialized.  Variables that are created on the stack (i.e. local variables) have garbage values, and thus should not be used before initializing.

A: one way is to define a construct function to initialize the params
typedef struct tagCtxt
{
    tagCtxt()
    {
     memset( iadl1, '\0', sizeof(char)*51);
     memset( iadl2, '\0', sizeof(char)*51);
     memset( iprurb, '\0', sizeof(char)*29);
     memset( iadl3, '\0', sizeof(char)*51);
    }
    char     iadl1[50+1];
    char     iadl2[50+1];
    char     iprurb[28+1];
    char     iadl3[50+1];
} PARM;


text:
Q: Overloading Getters In C++? Good day,
I am unsure how to describe the process I am inquiring about properly in one sentence so please excuse the title. I was searching for a way to ensure that users of a base class and or interface would assign data that would be regarded by the object itself and other objects in a non - default manner. So I have been doing the following:
struct ExampleInterface {
    virtual void SomeMethod() = 0;
    virtual std::string WhatLooksLikeAGetterButIsNot() = 0;
};

Here is a real world example:
//So states can be "poped in and out".//
struct State
{
    //To retrive what the active state is called.//
    /*Code In Question--->*/virtual std::string RegardStateAs() = 0;/*<---Code In Question*/
    virtual void ExecuteState( VRGE::MDNode* metaData ) = 0;
};

The idea would be to eventually do something such as
A (This option allows the problem trying to be prevented to occur if someone derives from "Update"):
struct Update : public State
{
    //Yadda yadda...//
    /*Code In Question--->*/std::string RegardStateAs() {
                                return std::string{ "Update" };
                            }/*<---Code In Question*/
};

B (This option does not allow what A does):
struct Update : public State
{
        //Yadda yadda...//
        //Not a good example, but the point gets across.//
        Update( std::string value ) {
            stateName = value;
        }
        /*Code In Question--->*/virtual std::string RegardStateAs() {
                                        return stateName;
                                 }/*<---Code In Question*/
            private:
               std::string stateName;

};

My question is: is this good or bad practice?
-----EDIT-----:
I do not have access to a compiler which can compile this, however it was pointed out to me that "override" would be perfect in this situation, for example:
//So states can be "poped in and out".//
struct State
{
    //To retrive what the active state is called.//
    /*Code In Question--->*/virtual std::string RegardStateAs() = 0;/*<---Code In Question*/
    virtual void ExecuteState( VRGE::MDNode* metaData ) = 0;
};

struct Update : public State
{
    //Yadda yadda...//
    /*Code In Question--->*/std::string RegardStateAs() override {
                                return std::string{ "Update" };
                            }/*<---Code In Question*/
};

A: As others have pointed out, your question is really addressing "overriding" (in the polymorphic sense), and not "overloading".
Assuming you want a fixed label for every subclass of State (static), your strategy works, but there are some limitations.  For clarity, I'm going to refer to your "RegardAsState" as "ToString".  If ToString needs to be called in the constructor of base class State, you'll have problems.  This is because the v-table entry of ToString for a derived class such as Update has not yet been established when executing a base class constructor.  A similar problem exists for calling ToString in State's destructor.
An alternative is to simply implement the state label as a const std::string in the base class State, and return it by const std::string & via a public get accessor.  It's a bit more efficient, both in eliminating the v-table indirection, and permitting return by const ref; and it eliminates the aforementioned ctor/dtor issues in State.
Even the suggestion above is not optimal, since there's no need to make this an instance method if the label is the same for every distinct State subclass.  If you want to get exotic, you could implement ToString as a static (stateless) accessor.  This can be done with a little known trick of passing a constant string as a template parameter like so:
template<const std::string & label>
struct State
{
    static const std::string & ToString()
    {
        return label;
    }
};

extern const std::string UpdateLabel = "Update";
State<UpdateLabel> Update;

// Or, with a bit of help from the macro preprocessor
#define DEFINE_STATE(stateClass) \
extern const std::string stateClass##Label = #stateClass; \
struct stateClass##State : State<stateClass##Label> \
// continue with definition of stateClass##State ... {}

DEFINE_STATE(Sample)
{
    // implementation of SampleState
};


text:
Q: Android dynamic feature stuck at installing view although it says it is installed I use dynamic feature module in my app and here is my App class -
@HiltAndroidApp
class DogApp : SplitCompatApplication() {

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        SplitCompat.install(this)
    }
}

Here is my MainActivity -
private var sessionId: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        fetchModules()
    }

    private fun fetchModules() {
        val splitInstallManager = SplitInstallManagerFactory.create(this)

        val request = SplitInstallRequest
            .newBuilder()
            .addModule("dogProfile")
            .build()

        val listener =
            SplitInstallStateUpdatedListener { splitInstallSessionState ->
                if (splitInstallSessionState.sessionId() == sessionId) {
                    when (splitInstallSessionState.status()) {
                        SplitInstallSessionStatus.INSTALLED -> {
                            Log.e("hi", "Installed")
                        }
                        SplitInstallSessionStatus.DOWNLOADING -> {
                            val totalBytes = splitInstallSessionState.totalBytesToDownload()
                            val progress = splitInstallSessionState.bytesDownloaded()
                            Log.e("hi", "Downloading$totalBytes...$progress")
                        }
                        SplitInstallSessionStatus.INSTALLING -> {
                            Log.e("hi", "Installing")
                        }
                    }
                }
            }

        splitInstallManager.registerListener(listener)

        splitInstallManager.startInstall(request)
            .addOnFailureListener { e -> Log.e("hi", "Exception: $e") }
            .addOnSuccessListener {
                Log.e("hi", "Success")
                sessionId = it
                val navHostFragment =
                    supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
                navHostFragment.navController.navigate(R.id.homeView)
            }
    }

When I build the apk and run on my device/emulator, I see "Installing Module" that stays forever
and I see the logs -
Installed

Success

Here is the screen I see forever -

What is the mistake I am doing?

A: Did you use navigation 2.3.2? I found there is an issue after this change. Rollback to 2.3.1 or use your own progress UI instead of DefaultProgressFragment will fix this issue.


text:
Q: LyX won't let me click on the new page + Won't allow blank lines I am using LyX with MikTex (LaTeX) sorry if I destroy some of these terms.. I am new here..
When I want to create a new page, I click on Insert -> formatting -> new page.
But it won't let me write in that section.. I am very frustrated as I've just downloaded everything and the second it sets up - it does not work.. How can I fix this issue?
Plus, it does not let me do force blank lines.. what is the purpose of this IDE if you can't do whatever you want? I really don't know.. (I tried pressing enter, shift+enter, go to insert->formatting -> rigged line but nothing works)
Thank you!

A: The problem of the new page I guess that is simply that you must  → to move the cursor after the new page line.

what is the purpose of this IDE if you can't do whatever you want?

Error. The purpose  of this IDE (and LaTeX) is not that, but allow you to write documents in a consistent and elegant format.
If you edit your question and type something, you will note that added extra spaces  and extra blank lines are ignored in the output. This is to maintain a consistent page layout of the web page.
LyX act similarly, but instead of ignoring your wrong decision at the output, ignore the input, to teach you that is wrong ...

*

*Add more than one space between words.

*force blank lines between paragraphs.

*Indent (or not indent) manually a paragraph.

*Put the authors before of the title.

*etc.

Some  of these actions are often careless mistakes  when typing, or worse, naive attempts to control  document layout like in a typewriter of the XIX century. LyX help in the first case, reverting the mistakes, and in the second case teach you that what you are trying is a job for LaTeX,  not for the user.
This mean that you cannot change the layout? Not at all. For instance, You can fix the spaces among all paragraphs automatically, and you can add some vertical spacers manually, but not accidentally as pressing Enter twice by error.